One Off the Slack: Are Large State Classes Performant?

Aaron Waller asked:

Does holding the screen state in large data classes negatively affecting the performance?

Aaron then points to a Stack Overflow question, where the asker worried about whether having a single view-state class with lots of properties might be worse than having several smaller ones. Basically, it boils down to whether recompositions will be more frequent or more expensive if the compositions react to changes in larger state objects.

Google’s Leland Richardson weighed in, with an answer of “its complicated”:

there’s sort of a tradeoff here, so unfortunately there’s no “do this, don’t do this” sort of answer.

On one side of the scale, where the size of the data class gets very very large, the answer is this may not be optimal if you’re just changing one property at a time. If the entire data class instance is being passed around through many composable scopes then this means they will all become invalid, since the data class instance is not equal to its prior value. on the other hand, if you’re just passing individual properties down to other scopes, then it may be fine, considering those values will have remained unchanged.

on the other side of the scale, you can imagine a very large number of mutable state objects, one for each tiny little piece of state in your app. On the one hand, this has nice properties in that when a small piece of that data is mutated, compose invalidates only in the scopes where each small little piece is used.

on the other hand, mutable state objects have some overhead, so you’ve added that overhead for every tiny piece of state

in general i am a fan of using immutable (all val) data classes to hold on to small-ish groups/collections of state that are semantically grouped together. so in other words, somewhere in the middle of that spectrum

finally, there may be some situations where state might be semantically coupled but it is beneficial to isolate one piecce of state into a mutable state object because it is being updated very rapidly and you want to minimize the scope of recomposition as much as possible. a value getting animated continuously is a good example of such a thing

IOW, focus less on the actual size of the state object and more on how much of the object’s content changes on a per-change basis, and how frequent those changes are.

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!