[英]Can someone explain why this test shows that jquery $.each is faster than native for?
I am running the following test in my browser console in Chrome. 我正在Chrome的浏览器控制台中运行以下测试。 I wanted to see how much faster native for is, only to find out that the results are showing jquery $each to be faster? 我想看看原生的速度快了多少,才发现结果显示jquery $ each更快? I know this is not true but i would like an explanation if possible. 我知道这不是真的,但如果可能的话,我想解释一下。
var array = new Array();
for (var i = 0; i < 10000; i++) {
array[i] = 0;
}
console.time('native');
var l = array.length;
for (var i = 0; i < l; i++) {
array[i] = i;
}
console.timeEnd('native');
console.time('jquery');
$.each(array, function(i) {
array[i] = i;
});
console.timeEnd('jquery');
native: 26.160ms
jquery: 5.665ms
If i put the same code inside a setTimeout() then the results are like this: 如果我将相同的代码放在setTimeout()中,则结果如下所示:
native: 0.123ms
jquery: 0.885ms
This is probably due to Chrome compiling functions and not compiling console input outside of functions. 这可能是由于Chrome编译功能,而不是在功能之外编译控制台输入。 Compiled functions run a lot faster. 编译的函数运行速度快得多。 jQuery.each
is already compiled (at the time jQuery was included on the page). jQuery.each
已被编译(在页面上包含jQuery时)。
Wrap your first test inside of an immediately-invoked function (which Chrome can compile before execution), and you'll see very similar results: 将您的第一个测试包装在立即调用的函数(Chrome可以在执行之前对其进行编译)的内部,您会看到非常相似的结果:
console.time('native');
(function(){
var l = array.length;
for (var i = 0; i < l; i++) {
array[i] = i;
}
})();
console.timeEnd('native');
console.time('jquery');
// ... unchanged
console.timeEnd('jquery');
native: 3.518ms
jquery: 3.308ms
That's why you were seeing radically difference results when you put code inside of a function in setTimeout
like setTimeout(function() { ... }, 1)
. 这就是为什么你当你把代码在函数内部被彻底看到差异导致setTimeout
喜欢setTimeout(function() { ... }, 1)
The code inside the function got compiled and ran a lot faster. 该函数内部的代码已编译并运行得更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.