Javascript 我应该使用 jQuery.each() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1883611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use jQuery.each()?
提问by pr1001
I'm doing very frequent iterations over arrays of objects and have been using jQuery.each(). However, I'm having speed and memory issues and one of the most called methods according to my profiler is jQuery.each(). What's the word on the street about its performance? Should I switch to a simple for loop? Of course I'm fixing the many issues in my own code too.
我正在对对象数组进行非常频繁的迭代,并且一直在使用 jQuery.each()。但是,我遇到了速度和内存问题,根据我的分析器,调用最多的方法之一是 jQuery.each()。街上有什么关于它的性能的词?我应该切换到一个简单的 for 循环吗?当然,我也在解决我自己代码中的许多问题。
采纳答案by Justin Swartsel
The source code for jQuery's each is as follows (Thank you John Resig and MIT License):
jQuery 的源代码如下(感谢 John Resig 和 MIT 许可):
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
}
As you can trace and see, in most cases it is using a basic for loop where the only overhead is really just the callback itself. Shouldn't make a difference in performance.
正如您可以跟踪并看到的,在大多数情况下,它使用基本的 for 循环,其中唯一的开销实际上只是回调本身。应该不会对性能产生影响。
EDIT: This is with the realization that selector overhead has already occurred and you are given a populated array object.
编辑:这是意识到选择器开销已经发生并且您得到了一个填充的数组object。
回答by Jace Rhea
This article(#3) ran some performance tests and found that the jQuery .each function was about 10x as slow as the native javascript for loop.
这篇文章(#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.
从立即提高 jQuery 性能的 10 种方法开始 - 3. 使用 For 而不是 Each
使用Firebug,可以测量这两个函数中的每一个运行所需的时间。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');上述结果对于本机代码为 2ms,对于 jQuery 的“each”方法为 26ms。如果我在我的本地机器上测试它并且他们实际上没有做任何事情(只是一个简单的数组填充操作),jQuery 的每个函数占用的时间是 JS 原生“for”循环的 10 倍以上。在处理更复杂的事情时,这肯定会增加,比如设置 CSS 属性或其他 DOM 操作操作。
回答by ChaosPandion
This method should give you a dramatic speed improvement.
这种方法应该会给你一个显着的速度提升。
var elements = $('.myLinks').get(), element = null;
for (var i = 0, length = elements.length; i < length; i++) {
element = elements[i];
element.title = "My New Title!";
element.style.color = "red";
}
Caching will also improve performance.
缓存也将提高性能。
function MyLinkCache() {
var internalCache = $('.myLinks').get();
this.getCache = function() {
return internalCache;
}
this.rebuild = function() {
internalCache = $('.myLinks').get();
}
}
In use:
正在使用:
var myLinks = new MyLinkCache();
function addMyLink() {
// Add a new link.
myLinks.rebuild();
}
function processMyLinks() {
var elements = myLinks.getCache(), element = null;
for (var i = 0, length = elements.length; i < length; i++) {
element = elements[i];
element.title = "My New Title!";
element.style.color = "red";
}
}
回答by MillsJROSS
Using native functionality will generally be fasterthan an abstraction, such as JQuery.each() method. However, the JQuery.each() method is easierto use and requires less coding on your part.
使用本机功能通常比抽象更快,例如 JQuery.each() 方法。但是,JQuery.each() 方法更易于使用并且需要您进行较少的编码。
Truthfully, neither one is the right or wrong choice without any context. I'm of the oppinion that we should be writing easier code first, assuming it's good/legilble/clean code. If you come into a situation, such as the one you're describing, where there's a noticeable lag, than it's time to find out where your bottlenecks are and write faster code.
说实话,没有任何背景,没有一个是正确或错误的选择。我认为我们应该首先编写更简单的代码,假设它是好的/易读/干净的代码。如果您遇到一种情况,例如您所描述的情况,其中存在明显的滞后,那么是时候找出瓶颈所在并编写更快的代码了。
Replacing the JQuery.each() method in these scenarios mighthelp, however, having not seen your code, it's possible you have bottlenecks unrelated to the JQuery method.
在这些场景中替换 JQuery.each() 方法可能会有所帮助,但是,如果没有看到您的代码,您可能会遇到与 JQuery 方法无关的瓶颈。
回答by a432511
One way to make sure you are getting the most out of jquery is to store the returned array of results in a variable rather than re-traversing the DOM everytime you need to get something.
确保您充分利用 jquery 的一种方法是将返回的结果数组存储在变量中,而不是每次需要获取某些内容时都重新遍历 DOM。
Example of what NOT to do:
不该做什么的例子:
$('.myLinks').each(function(){
// your code here
});
$('.myLinks').each(function(){
// some more code here
});
Better practice:
更好的做法:
var myLinks = $('.myLinks');
myLinks.each(function(){
// your code here
});
myLinks.each(function(){
// some more code here
});

