Hi, Hello everyone , This is Chengxiang Moying ！
Yes , I remember the password of the official account number ！
I’ve been in the pit recently Flutter, It coincides with Flutter Release 2.0, Formal full platform support , Then I’ll share some Flutter Relevant technical points , Today we start with
const Widget This is a small optimization point . Take a look at its principles and limitations .
stay Flutter in , is ” Everything is Widget”, and Widget The essence is the configuration of a set of information , It can be UI Exhibition , It can also be gestures 、 Navigation and other functions support . but Widget Designed to be immutable , Any change is made by destroying / The reconstruction has been modified , stay Widget Behind the immutability , Depend on Element variable / Reusable support , therefore Flutter take Widget The design is extremely lightweight , The cost of rebuilding is very low .
Some optimization techniques mention , In the build Widget When , have access to
const Widget, To get a similar 「 cache 」 The effect of . although Flutter It will reuse as much as possible Element, But if we cache directly Widget, Every reuse Widget, At least save Widget build Steps for .
const widget The optimization of the point , What is the principle behind it ？ Is the benefit of optimization big ？ Is it worth focusing on ？ Let’s talk about this today .
One 、const Constant
At the beginning of giving const add Widget front , Let’s start with Dart Linguistic const Keyword start .
Speaking of const, I have to mention something similar to it final, They all have the semantics of constants , That is, once assigned, it cannot be modified .
The difference is ,const Is a compile time constant , use const Constant decorated , Must be initialized at declaration time , And it’s a determinable value . and final Is the runtime constant , use final Constant decorated , Must be initialized at declaration time , Or initialize in the constructor , But its value can be calculated dynamically .
Don’t talk much , We last Demo It’s clear .
We use const When declaring class construction methods , Its related fields , Must be final Of , That is, after setting , It doesn’t change .
So one Dart Class object , Whether to allow const Modify to constant , Depending entirely on the class declaration , Whether the construction method is const modification .
As you can see from the above example , When using const Tectonic Point Object time , As long as it’s in the same parameter , You get the same object , For example ,p1 == p2 Output is true.
And once Point When the input parameters are different ,const And the objects after that are different , For example
p2 == p3 The output of false.
Okay , I won’t take you through the logic , Let’s compare the code and output carefully .
Mentioned earlier ,const Keyword modified constants , It must be a value that can be determined initially , That is to say, the assignment must also be a constant . For example, I’ll modify it a little bit
const Point() Input , Let it get it from a method , This leads to compilation failure .
Come here , We can come to a conclusion ： Use const Modifying constant objects , As long as the input parameters do not change during construction , We can get the same object .
The principle behind this , It’s nothing more than Dart VM The constant pool is implemented internally , Reuse the same objects with the Heyuan pattern .
Two 、const Widget
Speak clearly Dart Medium
const The meaning of and how to use , Next, we will Widget add , have a look
const Widget The principle of optimization .
stay Flutter in ,Widget Essence is just an element of information configuration , It’s defined as immutable , Any change reflects destruction & The reconstruction . and Widget The reason why immutability doesn’t affect efficiency very much , It’s because Element Realized with Widget The abstraction of change . That is, although Widget Will be rebuilt , however Widget Behind the scenes Element, But it’s reused .
meanwhile Flutter Framework, It has its own update strategy , Make sure Widget Change at the same time , Reuse as much as possible Element object .
The logic of this strategy is Element Of
updateChild() In the method , The method in Element It’s very important to build and update trees . We only care about the update process here , The father Element Node already has a child Element The node .
Father Element Node passing
updateChild() Method , Judge how to deal with your own children Element node , Is new 、 to update , Or just remove it .
updateChild() We can see that ,Element According to the new Widget When it’s updated , Will try to reuse the existing sub Element node , When it cannot be reused , Will pass
inflateWidget() Create a new child Element node .
updateChild() Yes 3 Input parameters , One of the key things is child and newWidget, They mean old respectively Element Child nodes and new Widget object .
Element It also holds Widget object , if child Held widget and newWidget When equal , Old and new Widget There is no change ,
updateChild() The logic is direct reuse child, I.e. old Element, No extra work will be done .
So if our Widget Defined as const, stay
updateChild() Update phase , Old and new Widget It’s the same object , It will not be rebuilt Widget, Behind it Element It will not be updated , Nature can play the role of cache reuse , Speed up the efficiency of building .
3、 … and 、const Widget Are you going to make a big profit ？
All optimization techniques are means , The optimization effect behind is our ultimate goal . A crazy operation , The output is not obvious , This is definitely not what we want .
that const Widget Is the effect of optimization obvious ？ It’s worth while we write code , Think about it , Is it necessary to use it in the current scene ？
Come to the conclusion first ： Don’t have to .
Since it’s optimization , A test, of course , Take the measured data , It’s the most important . Here I found @Cirzant Lai An example of sharing , It’s a good explanation , And then I’ll share some of my thoughts .
3.1 Look at the data
Here is a small program , Explicitly a random display Image.
That’s what we’re interested in Image Whether to use const Keyword construction for comparison .
Here’s how to use const Part of the code for the keyword .
Another reference program is not used const keyword .
This Image adopt AnimatedPositioned parts , Update location once per second . And then use
--profile Mode to run the program , And pass Dart DevTools Observe its “performance” and “memory”.
For the sake of analytical rigor , An older device was used for testing ：Sony Xperia Z2, If Flutter It’s still very easy to keep it on this device 60 Frame speed , It means that Flutter The optimization itself is already very good .
In addition to the equipment , To make the test data more obvious , There’s a gradual increase here Image The number of icons , When added to 1000 Time , The rendering time per frame is 80ms, It is about 12.5 FPS. I don’t think it’s necessary to continue to increase the number , This test is based on 1000 As boundary , Take… Separately 10、100、1000 Three sets of data , have a look “performance” and “memory” The performance of separation .
GPU & UI：
As you can see from the data shared above , When Image Yes 1000 When it’s time ,FPS I’ve been promoted 8.4%, Memory usage is down 20%. Although this data seems very obvious , But in practice ,2 There was no significant difference in fluency between the two tests .
in addition , We put it on a screen 1000 individual Image It’s not realistic , For most applications , Each screen can have dozens of Widget, It’s very rich . And if you need a lot of rendering , It’s better to use it directly Canvas Drawing improves efficiency , Not dependent const Widget This little bit of optimization .
3.2 const Yes GC The optimization of the
stay Flutter in ,Widget As configuration information , It’s designed to be very lightweight , To adapt to frequent destruction and reconstruction , This operation will inevitably lead to the old Widget Recycling of objects .
When we do const When the keyword declares a constant , Behind it is the concept of constant pool , take const Is cached in the constant pool , For subsequent reuse .
Constants have a longer life cycle for ordinary objects , It’s good and bad . The good thing is that constant objects do GC Not so sensitive , That is, it doesn’t need to be triggered frequently GC. The disadvantage is that the declaration period in constant pool is longer , It may result in the cache of infrequently used objects , There is no right time to release , Causes excessive memory usage .
Measured down ,const Indeed. GC There are some effects .
Here is the example from the previous article , Constantly create small Widget, In the end, we use const Before and after the occupancy of memory . You can see the use of const modification Widget after ,GC Less , And it’s smoother .
Here we should know , Use const Embellished Widget, Indeed. Flutter Of build There are some optimizations in the process , But optimization is not obvious . In use , We just need to use it on demand , There’s no need to pursue a lot of const turn .
A final summary , about Dart language .
One Dart Class objects can be used const modification , It depends on whether the constructor of the class is const modification ;
Use const In the construction method of modification , All members must be final modification ;
structure const Object time , It must also be const The constant ;
const Modifies the constructor , There can be no method ;
about Flutter Come on ,const The optimization point of decoration ：
Reuse with constant pool Widget, In the frequently updated Widget Scene , It has the function of optimization , Avoided Widget Recycling and reconstruction of the city ;
const Yes GC There is a certain inhibition around , In a scenario where a large number of identical objects will be created , There are fewer objects created , natural GC It’s going to be less ;
— End —
Did this article help you ？ Leaving a message. 、 forward 、 Some good-looking Is the greatest support , thank you ！