Why using for is faster than some() or filter()

前端 未结 3 1011
余生分开走
余生分开走 2021-01-14 01:20

I tried two different way to do something and I am surprised by the performance result :

I have 2 versions of a function :

Using a for :

3条回答
  •  遥遥无期
    2021-01-14 01:57

    Consider these two examples:

    for (var i = 0; i < array.length; i++) {
        doThing(array[i]);
    }
    

    vs.

    function processItem(item) {
        doThing(item);
    }
    for (var i = 0; i < array.length; i++) {
        processItem(array[i]);
    }
    

    This is basically the difference between the two. There also has to be some logic inside of filter and some for handling the return value from processItem but basically you're stacking a whole extra function call on top of your loop.

提交回复
热议问题