JavaScript: Why is native Array.prototype.map faster than looping in the Chrome console?

See an example here: http://jsperf.com/map-vs-for-basic, on the contrary, in the chrome console I get opposite results (the card is sometimes 6-10 times faster than for a loop). I would suggest that it will be the other way around.

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 
+4
source share
1 answer

First of all, your test is not realistic, because: the function is “run”, and updating the DOM web page is much slower than the difference between looping and using a “map”. That is, it is like comparing 100 m if every step the runners have to take coffee and write a book.

You must run a test with a very fast function.

Why is there a difference between browsers.

A map can be implemented inside:

  • Native / binary function with optimization: in this case, its use is much faster. Maybe Chrome is doing this.
  • As in the cycle, like you: in this case, the performance is similar, but an additional call to the "card" and internal checks may take a little more time.

Why embedded implementation is faster

Javascript is interpreted code, that is, the executable takes the source code and tries to perform the requested operations, but this means parsing the code and executing the resulting tree (a lot of work). Internal code is always much faster and optimized.

If the card is implemented using its own code, which allows optimization and much faster code than just a JS cycle (suppose that both implementations are correct and optimal).

+4
source

Source: https://habr.com/ru/post/1492880/


All Articles