简体   繁体   中英

JavaScript: Why is native Array.prototype.map faster than for loop in Chrome console?

See an example here: http://jsperf.com/map-vs-for-basic on the contrary, in the chrome console, I get the opposite results (map is sometimes 6-10 times faster than for loop). I would be guessing it's gonna be the opposite.

 var input = [];
 for(var i=0;i<10000;i++)input[i]=new Date(i);
    var output = [];

function perform(value,index){
    return value.toString()+index*index
}

console.time(1);output = input.map(perform);console.timeEnd(1);
// 1: 45.000ms

console.time(1);for(var i=0;i<input.length;i++)output[i]=perform(input[i],i);console.timeEnd(1);
// 1: 68.000ms

First of all, your test is not realistic because: the function "perform" and the update of the web page DOM is much slower than the difference between a loop and using "map". That is, it is like comparing a 100m rush if every step runners need to take a coffe and write a book.

You should do the test on a very fast function.

Why there is difference between browsers.

Map may be implemented internally as:

  • A native/binary function with optimization: in this case, his use is much faster. Chrome probably do do that.
  • Just as a loop, like you did: in this case, performance is similar, but the additional call to "map" and internal checks may take a few more time.

Why native implementation is faster

Javascript is interpreted code, that is, an executable take the source code and try to perform requested operations, but that mean to parse the code and execute the resulted tree (lot of job). Native code is always much faster and optimized.

If map is implemented with native code, that allow to perform optimization and a much faster code than just a JS loop (supposing that both implementations are corrects and optimal).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM