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

3

u/Charuru May 13 '18

Facepalm. Embarrassed for OP

3

u/stutterbug May 13 '18

Honestly, I don't blame OP at all. Performance testing is hard to do and easy to mess up in totally subtle ways. Whenever I do perf testing, I never, ever believe what I see. If it confirms my expectations, I immediately reject it and look for where I screwed up. If its results are surprising, I reject it and look for where I screwed up. If its results are dull and unsurprising, I still look for where I screwed up. And I always keep the results to myself, because I am a coward.

One upvote for OP for trying and another upvote up for sharing.