You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In theory, constness gives apps a performance boost, but during development these lints constantly nag developers: "Make this const" or "This cannot be const anymore". We should reevaluate if we are making the right trade-off here between naginess and performance.
For now we will limit our investigations to app developers and whether we should continue recommending the lints to them. We are not evaluating whether we should turn these lints off for the framework.
Reacted by Xavier H., Bruno Leroux, John Ryan, Wdestroier, Loïc Sharma, svn, Casey Rogers, Francesco Iapicca, Brian Wo, aniq and 6 more
In a very contrived benchmark (#148261) const ness was giving us a speed-up in build times of 13-16% on a Moto G4. However, the benchmark was very artificial and we should test it with something that's closer to a real world app. I am going to create a version of the flutter_gallery that doesn't use any const instantiations outside of the framework and see how a run of the transition benchmark compares to a constified flutter_gallery. I will run this on a mid-range Android phone with route snapshotting disabled.
Naginess
From playing around with this a bit with the flutter_gallery app, the biggest offenders here are prefer_const_constructors and prefer_const_literals_to_create_immutables. These constantly fire as you're iterating on your build method. And they are also often flip-flopping, what makes them even more annoying: You make a thing const because the lint told you so, then you iterate in a way that it cannot be const anymore and the analyzer yells at you again for that.
The prefer_const_constructors_in_immutables is the least annoying lint in the group. In fact, it is hardly annoying at all because it is fairly stable and as your code evolves you don't have to go back and forth on this one. Even if we disable the other lints, this one may be good to keep because it keeps the door open for developers to decide on a case by case basis if they want to be more strict and enable the other const lints. If we stop enforcing prefer_const_constructors_in_immutables they may no longer have the option to const-construct a widget because the widget may not offer a const constructor.
The prefer_const_declarations lint is in a bit of a grey area. It does not feel particularly annoying. But it also doesn't feel super-useful on its own without prefer_const_literals_to_create_immutables and prefer_const_constructors. So, if we end up disabling those I am leaning towards disabling this one as well.
Summary
Do more performance testing with a benchmark that's closer aligned with the real world. If constness doesn't make a huge difference (threshold TBD) recommend removing prefer_const_constructors, prefer_const_literals_to_create_immutables, and prefer_const_declarations from package:flutter_lints, but likely keep prefer_const_constructors_in_immutables. If constness makes a difference, we'll work with the language/analyzer team to figure out if we can make this less annoying (e.g. by introducing better quick fixes in the analyzer or by looking into introducing something like autoconst to the language).
Reacted by Wdestroier, Loïc Sharma, bigbott, Dillon and AndriyMatkivskiy
tl;dr: The benchmarks are not showing sufficient evidence to suggest that there is a statistically significant difference in performance between const and nonconst. I recommend removing prefer_const_constructors, prefer_const_literals_to_create_immutables, and prefer_const_declarations from package:flutter_lints.
I ran the benchmark mentioned in the previous post five times on the const version of the new_gallery app and five times on the nonconst version. A Mann-Whitney U Test with a standard confidence level of p=0.05 on the average frame build times (average_frame_build_time_millis) suggests no statistically significant difference between const and nonconst runs. In addition to that, I also ran a Student's T-Test on the individual unaggregated frame times of a randomly chosen specific const and nonconst benchmark run. At p=0.05 this one also suggests no statistically significant difference between const vs nonconst.
Given these results I suggest that we remove the prefer_const_constructors, prefer_const_literals_to_create_immutables, and prefer_const_declarations from package:flutter_lints. They don't seem to be carrying their weight, particularly when compared to how much annoyance they add when writing code. People, who still think these lints are worth it, can manually enable them in their analysis_options.yaml. I am also recommending that we keep prefer_const_constructors_in_immutables. This one is not annoying during development and it keeps the door open for downstream consumers of the widget to optionally create const instances of the widget if they so desire.
I am going to file a request over in the lints repository to have those lints removed.
Reacted by Greg Price, Bob Nystrom, Bruno Leroux, Michael Thomsen, Horace Bell-Gam, Britannio Jarrett, Victor Eronmosele, svn, Luke Pighetti, koodimetsa and 5 more
Reacted by _juliotati, Ale, Luca Venir, Nestor Sebastian Garzon Contreras and Sudhanta Suryaputra
Reacted by Brian Wo
Reacted by Xavier H., Sam Rawlins, Bob Nystrom, Bruno Leroux, Michael Thomsen, Loïc Sharma, svn, Wisp and bigbott
@goderbauer hi there, can you share the results, because spreadsheet is private.
Reacted by Mateus Felipe C. C. Pinto, Francesco Iapicca, Ale, Brian Wo, Mike Rydstrom, mono — Masayuki Ono, Đỗ Giáp Linh, Roman Preis, Artem Barkalov, Diego Garcia and 2 more
Hi @goderbauer. Thank you for running this analysis!
Other than frame build times, I'd expect the use of const might have an effect on memory usage and allocations. Was that measured by the test? As mentioned above, we don't have access to the raw data.
Can I ask if you considered running the performance benchmarks on other platforms as well?
From what I understood you only ran them on Android so far.
Would be interesting how this translates on other platforms, especially flutter web as performance has been one of the main pain points developers are complaining about when using flutter web.
I did quick benchmarks on core functionality before and the results from mobile vs web can be quite different.
Reacted by Mostafa Alazhariy, Sudhanta Suryaputra and Amir
I did a simple investigation, so, let me share my findings :-)
The const keyword significantly impacts widget performance, especially noticeable during numerous rebuilds across many widgets.
Here are some clarifications and enhancements to the discussion:
Performance Gains:
Using const can lead to performance improvements because it allows Flutter to reuse instances of immutable widgets across multiple rebuilds. This is particularly beneficial in complex UIs with many static elements.
Build and Instantiation:
There is a common confusion between “building” and “instantiating” in the official documentation that could be clarified. The term “building” often refers to invoking the build method, which describes the widget tree. In contrast, “instantiating” refers to creating an instance of a widget. Although a const widget can be rebuilt multiple times, its instance remains unchanged, thus saving on allocation and reducing garbage collection overhead.
Behavior in All Build Modes:
It’s crucial to understand that const is effective in all build modes (debug, profile, and release). The Dart VM optimizes performance by reusing const objects wherever possible, not just in release mode.
Selective Rebuilding:
Flutter optimizes the rebuilding process by not calling the build method on const widgets if their descendant widgets are not marked as dirty. For instance, if a parent widget is listening to a state change and contains a Column with a const widget as a child, and neither the child nor any descendants depend on the changed state, then the const widget will not be rebuilt. This selective rebuilding helps in further enhancing performance by avoiding unnecessary widget tree rebuilds.
A const widget creates a single, canonical instance when instantiated with the same parameters. This can be visualized as a cache where each unique set of parameters stores one instance of the widget.
You can have multiple const instances of the same widget class, each differentiated by its parameters.
classWidgetConstAextendsStatelessWidget {
finalString text;
constWidgetConstA({requiredthis.text});
// `operator ==` isn't overridden here, so comparison defaults to identity
}
classWidgetNonConstBextendsStatelessWidget {
finalString text;
WidgetNonConstB({requiredthis.text});
// `operator ==` isn't overridden here either
}
const widgetA1 =WidgetConstA(text:'A');
const widgetA2 =WidgetConstA(text:'A');
final isIdenticalA =identical(widgetA1, widgetA2); // prints `true`, same instancefinal isEqualA = widgetA1 == widgetA2; // prints `true`, identity implies equalityfinal widgetB1 =WidgetNonConstB(text:'B');
final widgetB2 =WidgetNonConstB(text:'B');
final isIdenticalB =identical(widgetB1, widgetB2); // prints `false`, different instancesfinal isEqualB = widgetB1 == widgetB2; // prints `false`, different instances
This distinction underscores the importance of const in managing memory efficiency and performance in Flutter applications. Both StatelessWidget and StatefulWidget can benefit from const constructors, with mutable state managed within the State.
Summary:
the const avoids re-instantiation of the const widget with the same const params, the instance is resolved during compilation time and it doesn't need to be collected by GC
Flutter Framework can skip calling the build method of the const widget during the re-building phase in case the child widgets are not marked as dirty, so, they don't need to be rebuilt
Reacted by Stanislav K, Raphael Porsche, tgloc, AndriyMatkivskiy, Paul Zarudnev and thanhle1547
This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.
Activity
goderbauer commentedon Jun 7, 2024
Performance
In a very contrived benchmark (#148261)
constness was giving us a speed-up in build times of 13-16% on a Moto G4. However, the benchmark was very artificial and we should test it with something that's closer to a real world app. I am going to create a version of the flutter_gallery that doesn't use anyconstinstantiations outside of the framework and see how a run of the transition benchmark compares to aconstified flutter_gallery. I will run this on a mid-range Android phone with route snapshotting disabled.Naginess
From playing around with this a bit with the flutter_gallery app, the biggest offenders here are
prefer_const_constructorsandprefer_const_literals_to_create_immutables. These constantly fire as you're iterating on your build method. And they are also often flip-flopping, what makes them even more annoying: You make a thing const because the lint told you so, then you iterate in a way that it cannot be const anymore and the analyzer yells at you again for that.The
prefer_const_constructors_in_immutablesis the least annoying lint in the group. In fact, it is hardly annoying at all because it is fairly stable and as your code evolves you don't have to go back and forth on this one. Even if we disable the other lints, this one may be good to keep because it keeps the door open for developers to decide on a case by case basis if they want to be more strict and enable the other const lints. If we stop enforcingprefer_const_constructors_in_immutablesthey may no longer have the option to const-construct a widget because the widget may not offer a const constructor.The
prefer_const_declarationslint is in a bit of a grey area. It does not feel particularly annoying. But it also doesn't feel super-useful on its own withoutprefer_const_literals_to_create_immutablesandprefer_const_constructors. So, if we end up disabling those I am leaning towards disabling this one as well.Summary
Do more performance testing with a benchmark that's closer aligned with the real world. If
constness doesn't make a huge difference (threshold TBD) recommend removingprefer_const_constructors,prefer_const_literals_to_create_immutables, andprefer_const_declarationsfrompackage:flutter_lints, but likely keepprefer_const_constructors_in_immutables. Ifconstness makes a difference, we'll work with the language/analyzer team to figure out if we can make this less annoying (e.g. by introducing better quick fixes in the analyzer or by looking into introducing something like autoconst to the language).goderbauer commentedon Jun 7, 2024
FYI @mit-mit @jonahwilliams @johnpryan @srawlins
goderbauer commentedon Jun 12, 2024
Related: dart-lang/sdk#53744
goderbauer commentedon Aug 16, 2024
Preparation of the gallery for benchmark running is in these two commits:
We will be benchmarking these two commits against each other using https://github.com/flutter/flutter/blob/8817d45220d582a0e56dea5119153c10a00d6d3e/dev/devicelab/bin/tasks/new_gallery__transition_perf.dart on a mid-range Android phone.
goderbauer commentedon Sep 5, 2024
tl;dr: The benchmarks are not showing sufficient evidence to suggest that there is a statistically significant difference in performance between const and nonconst. I recommend removing
prefer_const_constructors,prefer_const_literals_to_create_immutables, andprefer_const_declarationsfrompackage:flutter_lints.I ran the benchmark mentioned in the previous post five times on the const version of the new_gallery app and five times on the nonconst version. A Mann-Whitney U Test with a standard confidence level of p=0.05 on the average frame build times (average_frame_build_time_millis) suggests no statistically significant difference between const and nonconst runs. In addition to that, I also ran a Student's T-Test on the individual unaggregated frame times of a randomly chosen specific const and nonconst benchmark run. At p=0.05 this one also suggests no statistically significant difference between const vs nonconst.
The raw data for these statistical tests is at https://docs.google.com/spreadsheets/d/1g8redx2J9Y1veQO0aZJRgyixIT017sjozkL6OoU-7EE/edit?usp=sharing&resourcekey=0-5maj3yLJatvvB87Rt67OSA
Given these results I suggest that we remove the
prefer_const_constructors,prefer_const_literals_to_create_immutables, andprefer_const_declarationsfrompackage:flutter_lints. They don't seem to be carrying their weight, particularly when compared to how much annoyance they add when writing code. People, who still think these lints are worth it, can manually enable them in theiranalysis_options.yaml. I am also recommending that we keepprefer_const_constructors_in_immutables. This one is not annoying during development and it keeps the door open for downstream consumers of the widget to optionally create const instances of the widget if they so desire.I am going to file a request over in the lints repository to have those lints removed.
ext452 commentedon Sep 9, 2024
@goderbauer hi there, can you share the results, because spreadsheet is private.
xaethos commentedon Nov 13, 2024
Hi @goderbauer. Thank you for running this analysis!
Other than frame build times, I'd expect the use of
constmight have an effect on memory usage and allocations. Was that measured by the test? As mentioned above, we don't have access to the raw data.SteepSheep commentedon Nov 17, 2024
Can I ask if you considered running the performance benchmarks on other platforms as well?
From what I understood you only ran them on Android so far.
Would be interesting how this translates on other platforms, especially flutter web as performance has been one of the main pain points developers are complaining about when using flutter web.
I did quick benchmarks on core functionality before and the results from mobile vs web can be quite different.
ultraon commentedon Dec 2, 2024
I did a simple investigation, so, let me share my findings :-)
The
constkeyword significantly impacts widget performance, especially noticeable during numerous rebuilds across many widgets.Here are some clarifications and enhancements to the discussion:
Using
constcan lead to performance improvements because it allows Flutter to reuse instances of immutable widgets across multiple rebuilds. This is particularly beneficial in complex UIs with many static elements.There is a common confusion between “building” and “instantiating” in the official documentation that could be clarified. The term “building” often refers to invoking the build method, which describes the widget tree. In contrast, “instantiating” refers to creating an instance of a widget. Although a
constwidget can be rebuilt multiple times, its instance remains unchanged, thus saving on allocation and reducing garbage collection overhead.It’s crucial to understand that
constis effective in all build modes (debug, profile, and release). The Dart VM optimizes performance by reusing const objects wherever possible, not just in release mode.constwidgets if their descendant widgets are not marked as dirty. For instance, if a parent widget is listening to a state change and contains a Column with aconstwidget as a child, and neither the child nor any descendants depend on the changed state, then theconstwidget will not be rebuilt. This selective rebuilding helps in further enhancing performance by avoiding unnecessary widget tree rebuilds.constInstances:constwidget creates a single, canonical instance when instantiated with the same parameters. This can be visualized as a cache where each unique set of parameters stores one instance of the widget.constinstances of the same widget class, each differentiated by its parameters.This distinction underscores the importance of
constin managing memory efficiency and performance in Flutter applications. Both StatelessWidget and StatefulWidget can benefit fromconstconstructors, with mutable state managed within the State.Summary:
constavoids re-instantiation of theconstwidget with the sameconstparams, the instance is resolved during compilation time and it doesn't need to be collected by GCbuildmethod of theconstwidget during the re-building phase in case the child widgets are not marked as dirty, so, they don't need to be rebuiltgithub-actions commentedon Jan 3, 2025
This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of
flutter doctor -vand a minimal reproduction of the issue.