4

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
g00fy
  • 4,717
  • 1
  • 30
  • 46
  • the native method is supposed to be the fastest, because it is written in in the native browser language (c++). However, the results are not very consistent (and half a year ago, most native ES5 implementations where much slower). I had a discussion about the same issue: http://stackoverflow.com/questions/14647470/performance-of-jquery-grep-vs-array-filter – Christoph Jul 23 '13 at 07:04

1 Answers1

4

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).

Adrian Maire
  • 14,354
  • 9
  • 45
  • 85