Why is lodash.each faster than native forEach?

前端 未结 4 2003
别跟我提以往
别跟我提以往 2020-12-04 14:16

I was trying to find the fastest way of running a for loop with its own scope. The three methods I compared were:

var a = \"t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t         


        
4条回答
  •  忘掉有多难
    2020-12-04 14:39

    _.each() is not fully compatible to [].forEach(). See the following example:

    var a = ['a0'];
    a[3] = 'a3';
    _.each(a, console.log); // runs 4 times
    a.forEach(console.log); // runs twice -- that's just how [].forEach() is specified
    

    http://jsfiddle.net/BhrT3/

    So lodash's implementation is missing an if (... in ...) check, which might explain the performance difference.


    As noted in the comments above, the difference to native for is mainly caused by the additional function lookup in your test. Use this version to get more accurate results:

    for (var ix = 0, len = a.length; ix < len; ix++) {
      cb(a[ix]);
    }
    

    http://jsperf.com/lo-dash-each-vs-native-foreach/15

提交回复
热议问题