For Array, is it more efficient to use map() & reduce() instead of forEach() in javascript?

后端 未结 4 1121
一整个雨季
一整个雨季 2021-01-19 01:41

1)As we know, there\'s no side-effect with map() and reduce(). Nowadays, we also have muti-core on cell phone. So is it more efficient to use them?

2)On the other h

4条回答
  •  梦谈多话
    2021-01-19 01:46

    I just tested this today, using map and reduce over floating point numbers, with the latest node.js version, and the answer is that map and reduce was two orders of magnitude slower than an regular for loop.

    var r = array.map(x => x*x).reduce( (total,num) => total+num,0);
    

    ~11,000ms

    var r = 0.0;
    array.forEach( (x,i,a) => r += x*x  )
    

    ~300ms

    var r = 0.0;
    for (var j = 0; j < array.length;j++){
        var x = array[j];
        r += x*x;
    }
    

    ~35ms

    EDIT: One should note that this difference is much less in Firefox, and may be much less in future version of Node / Chrome as well.

提交回复
热议问题