Can keys help with performance?

In this article, I talk through how I improved the performance of a package via a simple refactor.

3 Likes

As discussed in flutter/flutter#156551, I don’t believe there’s a situation where a widget’s key can be used to prevent rebuilds.

how would you explain the performance improvements then?

Good question!

It looks like the linked article identified 2 concepts:

  1. Use of function-based widgets (i.e. performance can be improved by implementing a new widget instead of using a helper function)
  2. Specifying keys

I believe that #1 impacts performance but #2 does not—keys are designed for tracking a widget’s identity; by default they don’t prevent rebuilds.

hmm, so to test that you could use the original package and only add the keys and see if it changes anything :wink:

2 Likes

Looks like I need to further test my hypothesis.

  1. Test function returned Widget but with keys.
  2. Test class widget without keys
  3. Plus other permutations

The results would conclusively tell if keys or using classes made the difference, or the combination of both.

I was of the opinion that keys serve something as identifiers of nodes in the element tree, and may help prevent rebuilds therefore if the node it identifies isn’t dirty during traversal. However without keys I reasoned that the engine sees the widget returned by the builder as a newly injected node requiring a rebuild.

Feel free to check out the Key docs!

Keys can do a few cool things:

  • Rebuilding with a different key will reset the BuildContext (and State) entirely.
  • Widgets with multiple children (like ReorderableListView) use keys to keep track of which child is which.
  • A GlobalKey allows a widget to relocate to anywhere in the tree, and maintain its State.

There’s an important distinction: Keys determine whether an Element resets, not whether it rebuilds.

1 Like

@nate-thegrate what exactly does resets mean in this context?

It means that a new BuildContext (a.k.a. Element) is created, and the old one is disposed of. Since a stateful widget’s State is stored in the Element, the state is disposed & re-created as well.

Here’s a DartPad example!

4 Likes