Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash take v JavaScript slice performance

I have an array of length 100,000,000.

When max is nearly at the end of the array, this takes about 8 seconds:

return _.take(numbers, max)

This takes about 1 second:

return numbers.slice(0, max)

Why the massive performance difference?

like image 303
danday74 Avatar asked Jun 27 '26 04:06

danday74


1 Answers

Lodash uses its own implementation of slice (in the bundled version called baseSlice) array method which you can see here.

One of the main premises of lodash is browser compatibility which they achieve in most of the cases by having lodash version of various methods.

Good example is _.take as well as _.slice/_.tail/_.chunk/_.drop/_.dropRight/_.initial etc methods which all under the cover utilize the baseSlice method and do not rely on the native Array.slice

So if you compare native vs lodash you would find native winning consistently, but that is not what makes lodash shine ... at-least prior ES6 that is.

like image 114
Akrion Avatar answered Jun 29 '26 17:06

Akrion