Oct 20 2020
JS Performance: Classes vs Function Composition
Today during lunch I wrote up a really quick benchmark comparing the performance of class instantiation vs function composition.
Overview: Class instantiation is about 25x faster than function composition.
The benchmarks below represent the time it takes to do 10,000,000 executions. 10 trial runs were completed where you can find the min, max, and average spanning the trial runs.
----- CLASS ----- min: 5.5ms max: 13.9ms average: 7.5ms ----- FUNCT ----- min: 159.3ms max: 201.5ms average: 170.1ms
What implications does this have? Typically in a Redux store, the selectors portion of the codebase use function composition. From this basic benchmark, it would suggest that having a read-only class solely with getter functions would be preferable to what’s currently the standard. Note that this does not take memoization into account since both function composition and getter methods can support caching.
Why is this important? Selector code is ran a lot since it is part of a components lifecycle. Each render has the potential to re-run selector code. When given hundreds or thousands of selectors in a mature codebase, performance slowly becomes an issue. Also consider that selectors can functionally compose other selectors (which can compose even more selectors).
Is it that big of a deal? Probably not. In a mature codebase, there is most definitely larger fish to fry when improving performance. In any case, I hope this read was interesting.
Benchmark code can be found in my git repo