javascript - 我应该使用 jQuery.each() 吗?

标签 javascript jquery arrays iteration each

我对对象数组进行非常频繁的迭代,并且一直在使用 jQuery.each()。但是,我遇到了速度和内存问题,根据我的探查器,调用次数最多的方法之一是 jQuery.each()。街上对其性能有何评价?我应该切换到简单的 for 循环吗?当然,我也在修复我自己代码中的许多问题。

最佳答案

This article (#3) 进行了一些性能测试,发现 jQuery .each 函数的速度大约是原生 javascript for 循环的 10 倍。

From 10 Ways to Instantly Increase Your jQuery Performance - 3. Use For Instead of Each
Using Firebug, it's possible to measure the time each of the two functions takes to run.

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');

The above results are 2ms for native code, and 26ms for jQuery's "each" method. Provided I tested it on my local machine and they're not actually doing anything (just a mere array filling operation), jQuery's each function takes over 10 times as long as JS native "for" loop. This will certainly increase when dealing with more complicated stuff, like setting CSS attributes or other DOM manipulation operations.

关于javascript - 我应该使用 jQuery.each() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1883611/

相关文章:

javascript - jQuery - 在代码行之前查找特定元素

javascript - 在 JavaScript 中定义函数的参数列表

javascript - 如何操作多个数组中的相同元素

javascript - 如何在禁用时更改按钮的颜色然后在启用时返回

javascript - 我不知道如何在页面末尾加载第二次帖子

Javascript:检查数组中的任何元素是否包含字符串的一部分

javascript - 如何设置最小列宽Column Resizing Js

javascript - jQuery 通过 $(this) 遍历 HTML

c++ - for_each 和 ranged base for on 2D array

javascript - angularjs http post 到特定元素处的 json 数组