有人可以解释为什么这个测试表明 jquery $.each 比 native for 快吗?

Can someone explain why this test shows that jquery $.each is faster than native for?

我运行在我的浏览器控制台中Chrome进行以下测试。我想看看 native for 的速度有多快,却发现结果显示 jquery $each 更快?我知道这不是真的,但如果可能的话我想要一个解释。

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

如果我将相同的代码放在 setTimeout() 中,那么结果如下:

native: 0.123ms
jquery: 0.885ms

这可能是由于 Chrome 编译函数而不是编译函数外的控制台输入。编译函数 运行 快了很多。 jQuery.each 已经编译(当时 jQuery 被包含在页面上)。

将你的第一个测试包装在一个立即调用的函数中(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

这就是为什么当您将代码放入 setTimeout 中的函数(如 setTimeout(function() { ... }, 1) 时)会看到截然不同的结果。函数内的代码得到了编译并且 运行 快了很多。