简体   繁体   English

JavaScript:为什么原生Array.prototype.map比Chrome控制台中的循环更快?

[英]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). 在这里看一个例子: http//jsperf.com/map-vs-for-basic相反,在chrome控制台中,我得到相反的结果(map有时比循环快6-10倍)。 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". 首先,你的测试是不现实的,因为:函数“执行”和网页DOM的更新比循环和使用“map”之间的差异要慢得多。 That is, it is like comparing a 100m rush if every step runners need to take a coffe and write a book. 也就是说,如果每一步跑步者都需要喝咖啡并写一本书,那就像是比较100米的冲刺。

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. Chrome可能会这样做。
  • 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. 就像你做的一样循环:在这种情况下,性能类似,但额外调用“map”和内部检查可能需要更多时间。

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). Javascript是解释代码,也就是说,可执行文件采用源代码并尝试执行请求的操作,但这意味着解析代码并执行结果树(大量工作)。 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). 如果使用本机代码实现map,那么允许执行优化和比仅仅JS循环更快的代码(假设两个实现都是纠正和最佳)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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