Reputation: 4737
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
Upvotes: 4
Views: 3646
Reputation: 14845
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:
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).
Upvotes: 5