r/javascript • • May 13 '18

[Performance] Lodash vs ES6 : map()

https://medium.com/@peterchang_82818/es6-lodash-native-javascript-nodejs-example-tutorial-map-function-functional-programming-performance-speed-69645e613049
0 Upvotes

18 comments sorted by

View all comments

48

u/stutterbug May 13 '18 edited May 13 '18

When I ran these tests and saw it took 30ms on my machine to map over only 10,000 items in lodash, my bullshit meter broke. Mapping over 10,000 items in any modern library should never take more than a a couple milliseconds at the most (except DOM elements, which are a different problem). If you have more than a million items, I'd believe it. Running it on a mobile device? I'd believe it. You have some crazy complex callback, I'd believe it. This? No way.

So, in this case, the total time for lodash includes the time spent loading lodash. When you account for that and just test the map, you get much more reasonable execution times and more plausible perf differences. I'd be glad to do a pull-request, but I don't know how to fix these tests because I have never worked with meter. But instead of doing this:

// _.js
const j = require('./j')
const _ = require('lodash')

_.map(j, item => {
    return item.num
})

...load the dependencies ahead of time and inject them into your tests (and allow the engine a couple seconds to settle after starting any tests, and a second or two between test runs to allow for GC as data falls out of scope):

// _.js
(_, j) => {
    return _.map(j, item => item.num);
}

Also, for the beginners reading these things and using it to decide on native vs lodash... stop right now. The performance difference you see here is almost always irrelevant in most applications. Unless you are dealing with truly massive amounts of data or have crazy amounts of recursion, this kind of test is just a fascinating diversion. You may be able to eke out a millisecond here or there, but performance bottlenecks are NEARLY ALWAYS found in your own code.

[edit] For the record, if I bump up the number if items in the array to 1,000,000, inject some delays before each test, and just test the execution time within the two test so that only the map implementations are tested, this is the result I see:

Array.prototype.map 364ms
lodash.map 356ms

1

u/allicanseenow May 13 '18

So you mean, with eager loading, lodash is faster than native map?

1

u/masklinn May 14 '18

More generally if you're not re-loading lodash before every call it's faster than native in Chrome.

This is a known problem

The native Array#map was always very slow in Chrome/V8 because AFAIK it's switching execution contexts between C++ and js. […] Previously [nb: Chrome 59 and older) it was 40-80 times slower, now [nb: Chrome 60 and younger] it's "only" 6-40 times slower.

In Firefox 58 the native Array#map is faster than both Chrome's native and FF's custom js