Standardizing Selector Styles.
When selecting state out of our store we’ve written a collection of selectors to consolidate selectors logic. We’ve always write these selectors in array notation to keep styles consistent.
messageStore.getIn([id, 'author', 'screenname']);
With all selectors written in array notation, for Immutable.js we use
.getIn() by default — regardless if the path is only one key deep. It’s very convenient. Keeps our selectors looking consistent in shape.
However it is always faster to do a
.get() instead of a
.getIn() . For
.getIn() Immutable.js has to iterate through an array path and check the result for each key path along the way. This therefore makes
.getIn() expensive and
.get() ultimately cheaper.
So if we wish to keep all selectors a consistent array path style, but take advantage of the speed of
.get() whenever possible we could make a get abstraction. The first thing to do is to create an abstraction for Immutable
.getIn() — something like this:
.get() to the abstraction.
How could we get this handy abstraction to take advantage of
.get() whenever possible?
We could peak into the
arrayPath , if there is only one value, use plain old
.get(). Seems simple enough.
But is it performant?
Array length checking is cheap. With a quick little JSPerf test we can see immediately takins the time to check if we should use
.get() is more than twice as fast than just always using
In the end
In the end, this is a micro optimization. However, we saw ~50ms to ~150ms speedups for every actions in the app. It really depends on the how often your selectors run. We have a large number of selectors that fire quite a bit. For such a small change, we’ll gladly take any performance boost over 100ms.
Don’t worry about the abstraction, just remember to prefer
.getIn() whenever possible.
Pro tip: Same goes for