Map

JS Micro-Perf: Array.map by Zach Mayer

Today I had a familiar argument regarding Javascript micro-optimizations. This time we were mulling the virtues and vices of Array functions like map, reduce, filter, etc., and the performance variance among different implementations (underscore/lodash, Array.prototype, home-grown and such). As always my first stop was jsperf.com.

Take a look at these results:

Source: JSPerf.com

Pretty much what you expected right? The Array.prototype.map function is like, 5 to 7 times slower than underscore/lodash and 18 times slower than a plain old for loop. Even jQuery's notoriously slow map function beats it.

What struck me however was that there are a couple of ways to make that for loop above even faster so I wanted to see just how fast it could go. That led me to create this micro-perf-test:

Source: JSPerf.com

More than doubled the performance of the map by simply allocating the array up front and avoiding "push" overhead. Moral of the story? Allocation is expensive. Pay attention to your heap changes the same way you care about repaint/reflow and your apps will run like the wind.

Of course, these kinds of micro-optimizations often as not aren't worth the code bloat and subsequent headache to maintain over a nice, handy library function, but it's helpful to know that the native Array.prototype functions are simply dog slow and almost anything will perform better.

Counter-intuitive, but the data speaks.

OUT.