颤振稳定性叶瓣图_颤振性能优化

本文深入探讨Flutter应用的颤振稳定性,通过分析叶瓣图来提升性能。通过对颤振稳定性叶瓣图的理解,开发者可以优化其 Flutter 应用,减少不必要的帧率下降,提供更流畅的用户体验。
摘要由CSDN通过智能技术生成

颤振稳定性叶瓣图

Ever wondered how flutter handles all your UI building and events like Futures, taps, etc.. on a single thread( yes it does all that on a single thread 😮😮😮 until and unless explicitly done).

曾经想知道flutter如何在单个线程上处理所有UI构建和事件,例如Future,taps等。(是的,它在单个线程上完成所有操作😮😮😮直到并且除非明确完成)。

什么是线程/隔离? (What is Thread/Isolates ?)

Thread is an independent process that has its own chunk of memory and executes the given instructions on that memory , It can work parallelly with other threads hence can reduce execution time of multiple process on a single thread .

线程是一个独立的进程,具有自己的内存块并在该内存上执行给定的指令。它可以与其他线程并行工作,因此可以减少单个线程上多个进程的执行时间。

Let’s understand this with an example :

让我们通过一个例子来理解这一点:

In Fps games like counter strike, Call of duty, etc. you can see that as soon as you fire a weapon few tasks executes simultaneously like playing of bullet sound, change of bullet count and reduction in opponent health , All these things happens parallelly these are basically threads which execute parallelly and execute their task on separate isolates(isolates and threads can be used interchangeably as isolate is a Dart way of multi threading more on that below) which have its own memory.

在Fps游戏中,例如反恐精英,使命召唤等,您可以看到,一旦发射武器,几乎没有同时执行的任务,例如弹奏子弹声,改变子弹数和减少对手的生命值,所有这些并行发生基本上是并行执行并在单独的隔离上执行其任务的线程(隔离和线程可以互换使用,因为隔离是Dart在下面的更多内容中介绍的多线程方法),它具有自己的内存。

Languages like JAVA and C++ Share Their heap memory with threads, but in case of flutter, every isolate has its own memory and works independently. As it has its own private space this memory doesn’t require locking, as if a thread finishes its task it already means that the thread has finished utilizing its memory space and then that memory can go for garbage collection.

诸如JAVA和C ++之类的语言与线程共享它们的内存,但是在出现混乱的情况下,每个隔离都有自己的内存并且可以独立工作。 由于该内存具有自己的私有空间,因此不需要锁定,就好像一个线程完成了它的任务一样,这意味着该线程已经完成了对它的内存空间的利用,然后该内存可以用于垃圾回收了。

To maintain these benefits flutter has a separate memory for every isolate(Flutter way of multi-threading) that’s why they are called isolate 🙂.

为了保持这些好处,flutter为每个隔离(Flutter的多线程方式)都有一个单独的内存,这就是为什么它们被称为isolate🙂。

Learn more about isolates below.

在下面了解有关隔离株的更多信息。

它对我有什么帮助?在哪里应该使用隔离/线程? (How can it be helpful to me and where should I use isolates/Threads?)

何时使用隔离/线程? (When to use isolates/threads ?)

There are a few situations where isolates can be very handy.

在某些情况下,隔离很方便。

  1. Let say you want to execute a network call and you want to process that data that you just received . and that data contains about million records that alone will hang your UI.

    假设您要执行网络呼叫,并且要处理刚收到的数据。 并且这些数据包含大约一百万条记录,仅此一项就会挂起您的UI。
  2. You have some image processing tasks that you want to do on-device these kinds of tasks are highly computational as they have to deal with lots of number crunching operations which may lead to frozen UI or legginess in UI.

    您有一些要在设备上执行的图像处理任务,这些类型的任务需要大量的计算,因为它们必须处理大量的数字运算操作,这可能会导致UI冻结或UI出现问题。

So to conclude when to use isolates, We should use them whenever you think there is a lot of computation that needs to be offloaded from the main thread.

因此,总结一下何时使用隔离符,只要您认为需要从主线程中卸载大量计算,就应该使用它们。

如何使用隔离株? (How to use isolates ?)

Flutter team has designed a very elegant and abstract way of using isolates/threads in a flutter, Using compute we can do the same task which isolates does but in a more cleaner and abstract way. Let’s take a look at the flutter compute function.

Flutter团队设计了一种在flutter中使用隔离/线程的非常优雅和抽象的方法。使用计算,我们可以执行与isolates相同的任务,但使用的方法更加简洁和抽象。 让我们看一下Flutter 计算功能。

Syntax:

句法:

var getData = await compute(function,parameter);

Compute function takes two parameters :

计算功能采用两个参数:

  1. A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level).

    未来或功能,但必须是静态的(如dart线程不共享内存,因此它们是类级别的成员,而不是对象级别的成员)。
  2. Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).

    要传递给函数的参数,要发送多个参数,可以将其作为映射传递(因为它仅支持单个参数)。

compute function returns a Future which if you want can store into a variable and can provide it into a future builder.

计算函数返回一个Future,如果需要,可以将其存储到变量中并将其提供给future构建器。

Let’s start by analyzing a sample problem:

让我们开始分析一个样本问题:

import 'dart:io';


import 'package:flutter/material.dart';


class With10SecondDelay extends StatelessWidget {
  runningFunction() {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
      sleep(Duration(seconds: 1));
      print(i);
      sum += i;
    }
    return "total sum is $sum";
  }


  pauseFunction() {
    //pause function is not async
    print(runningFunction());
  }


  @override
  Widget build(BuildContext context) {
    pauseFunction();
    return Material(
      child: Center(
        child: Center(
          child: Text(
            "Tnx for waiting 10 seconds : check console for response",
            style: TextStyle(
              fontSize: 50,
            ),
          ),
        ),
      ),
    );
  }
}

In the above code pausefunction() is called just below the build method which pauses the execution of code for 10 seconds. And because of that when you try to navigate to this page from a previous one there will be a delay of ten seconds before our page gets pushed on to the widget tree.

在上面的代码中,在build方法正下方调用了pausefunction(),该方法将代码的执行暂停10秒钟。 因此,当您尝试从上一个页面导航到该页面时,将有十秒钟的延迟,然后我们的页面被推到小部件树上。

We can try to resolve this issue by using async.

我们可以尝试使用异步解决此问题。

pauseFunction() async {
    //pause function is async
    print(runningFunction());
  }

As you can see now we have declared our pause function as async even doing this will not help

如您现在所见,我们已经将暂停功能声明为异步,即使这样做也无济于事

As async in dart is basically puts our code in ideal until there is something to compute so it seems to us that dart is executing these on a different thread but actually it’s just waiting for some event to occur in that async function.

由于dart中的async基本上使我们的代码处于理想状态,直到可以进行计算为止,因此在我们看来dart在不同的线程上执行这些操作,但实际上它只是在等待该async函数中发生的事件。

More on async below :

以下是有关异步的更多信息:

Let’s solve the above issue using compute.

让我们使用compute解决上述问题。

import 'dart:io';


import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';


class ComputeWith10SecondDelay extends StatelessWidget {
  static Future<String> runningFunction(String str) async {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
      await Future.delayed(Duration(seconds: 1));
      print(i);
      sum += i;
    }
    return "Sum is : " + sum.toString() + str;
  }


  pauseFunction() async {
    print(await compute(runningFunction,
        " This is an argument")); //storing data of copute result
  }


  @override
  Widget build(BuildContext context) {
    pauseFunction();


    return Material(
      child: Center(
        child: Center(
          child: Text(
            "Wow , it saved my 10 seconds : check console for response",
            style: TextStyle(
              fontSize: 50,
            ),
          ),
        ),
      ),
    );
  }
}

In the above code, we basically passed our function in compute() function and that creates a separate isolate to handle the task and our main UI will still run without any delay (check the debug console for response ).

在上面的代码中,我们基本上将函数传递给了compute()函数,并创建了一个单独的隔离来处理任务,我们的主UI仍将无任何延迟地运行(请检查调试控制台以获取响应)。

Summary:

摘要:

  1. Dart is by default executes all its code on a single-threaded.

    默认情况下,Dart是在单线程上执行其所有代码。
  2. Every function and every async-await calls work only on the main thread(until and unless specified).

    每个函数和每个async-await调用仅在主线程上起作用(直到指定,除非指定)。
  3. We can create multiple threads using compute( Future function/normal function, argument).

    我们可以使用compute(Future function / normal function,arguments)创建多个线程。
  4. You can use compute for executing network calls, performing number-crunching calculations, image processing, etc.

    您可以使用计算来执行网络呼叫,执行数字运算,图像处理等。

This is all about compute to learn more about isolates (the underlying architecture of computing function) check out isolate .

这就是关于计算的全部内容,以了解有关隔离的更多信息(计算功能的基础体系结构)签出隔离

Thanks for reading this article.

感谢您阅读本文。

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

如果您觉得有趣,请拍手! 如果您发现任何错误,请告诉我,感谢您的贡献。

Check out full code at FlutterDevs GitHub.

在以下位置查看完整代码 FlutterDevs GitHub。

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

FlutterDevs的Flutter开发人员团队可构建高质量且功能丰富的应用程序。 根据您的要求,每小时或全时为您的跨平台Flutter移动应用程序项目雇用flutter开发人员 ! 您可以在FacebookGitHubTwitterLinkedIn 与我们联系,以获取任何与抖动相关的查询。

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

我们欢迎您提供反馈,并希望您分享使用#FlutterDevs所做的工作 。 我们非常高兴看到您如何使用Flutter建立美好的交互式Web体验!

Image for post

翻译自: https://medium.com/flutterdevs/flutter-performance-optimization-17c99bb31553

颤振稳定性叶瓣图

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值