我对对象数组进行非常频繁的迭代,并且一直在使用 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/