Skip to content

Investigate constness #149932

Closed
Closed

Description

@goderbauer

We would like to investigate if the following lints related to const (which are currently enabled by package:flutter_lints) are carrying their weight:

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.

Activity

  1. self-assigned this
    on Jun 7, 2024
  2. goderbauer commented on Jun 7, 2024

    @goderbauer
    MemberAuthor

    Performance

    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).

  3. goderbauer commented on Jun 7, 2024

    @goderbauer
    MemberAuthor
  4. goderbauer commented on Jun 12, 2024

    @goderbauer
    MemberAuthor
  5. goderbauer commented on Aug 16, 2024

    @goderbauer
    MemberAuthor

    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.

  6. goderbauer commented on Sep 5, 2024

    @goderbauer
    MemberAuthor

    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.

    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, 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.

  7. ext452 commented on Sep 9, 2024

    @ext452

    @goderbauer hi there, can you share the results, because spreadsheet is private.

  8. xaethos commented on Nov 13, 2024

    @xaethos

    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.

  9. SteepSheep commented on Nov 17, 2024

    @SteepSheep

    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.

  10. ultraon commented on Dec 2, 2024

    @ultraon

    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:

    1. 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.
    2. 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.
    3. 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.
    4. Selective Rebuilding:
    1. Understanding const Instances:
    • 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.
    class WidgetConstA extends StatelessWidget {
      final String text;
      const WidgetConstA({required this.text});
      // `operator ==` isn't overridden here, so comparison defaults to identity
    }
    
    class WidgetNonConstB extends StatelessWidget {
      final String text;
      WidgetNonConstB({required this.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 instance
    final isEqualA = widgetA1 == widgetA2;               // prints `true`, identity implies equality
    
    final widgetB1 = WidgetNonConstB(text: 'B');
    final widgetB2 = WidgetNonConstB(text: 'B');
    final isIdenticalB = identical(widgetB1, widgetB2);  // prints `false`, different instances
    final 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
  11. github-actions commented on Jan 3, 2025

    @github-actions

    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.

  12. locked as resolved and limited conversation to collaborators on Jan 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions