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

发布于 2024-08-14 11:31:27 字数 144 浏览 3 评论 0 原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

许仙没带伞 2024-08-21 11:31:27

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

来自 立即提高 jQuery 性能的 10 种方法 - 3. 使用 For 而不是 Each
使用 Firebug,可以测量这两个函数各自运行所需的时间。< /p>

var array = new Array();
for (var i=0; i<10000; i++) {
    数组[i] = 0;
}

console.time('本机');
var l = array.length;
for (var i=0;i

上面的结果对于本机代码是 2ms,对于 jQuery 的“each”方法是 26ms。假设我在本地机器上测试了它,并且它们实际上没有做任何事情(只是一个数组填充操作),jQuery 的每个函数花费的时间是 JS 原生“for”循环的 10 倍以上。当处理更复杂的东西时,比如设置 CSS 属性或其他 DOM 操作操作,这肯定会增加。

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.

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.

垂暮老矣 2024-08-21 11:31:27

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;
}

正如您可以跟踪和看到的,在大多数情况下,它使用基本的 for 循环,其中唯一的开销实际上只是回调本身。不应该对性能产生影响。

编辑:这是因为意识到选择器开销已经发生,并且您得到了一个填充的数组对象

The source code for jQuery's each is as follows (Thank you John Resig and MIT License):

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.

EDIT: This is with the realization that selector overhead has already occurred and you are given a populated array object.

尘世孤行 2024-08-21 11:31:27

这种方法应该可以显着提高速度。

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";
}

缓存也将提高性能。

function MyLinkCache() {
    var internalCache = $('.myLinks').get();

    this.getCache = function() {
        return internalCache;  
    }

    this.rebuild = function() {
        internalCache = $('.myLinks').get();
    }
}

使用中:

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";
    }
}

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";
    }
}
蔚蓝源自深海 2024-08-21 11:31:27

确保充分利用 jquery 的一种方法是将返回的结果数组存储在变量中,而不是每次需要获取某些内容时都重新遍历 DOM。

不应该做什么的示例:

$('.myLinks').each(function(){
    // your code here
});
$('.myLinks').each(function(){
    // some more code here
});

更好的做法:

var myLinks = $('.myLinks');
myLinks.each(function(){
    // your code here
});
myLinks.each(function(){
    // some more code here
});

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.

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
});
请远离我 2024-08-21 11:31:27

使用本机功能通常比抽象更快,例如 JQuery.each() 方法。然而,JQuery.each() 方法更容易使用,并且需要更少的代码。

说实话,没有任何背景,任何一个选择都不是正确或错误的。我认为我们应该首先编写更简单的代码,假设它是好的/易读的/干净的代码。如果您遇到一种情况,例如您所描述的情况,存在明显的滞后,那么是时候找出瓶颈所在并编写更快的代码了。

在这些场景中替换 JQuery.each() 方法可能会有所帮助,但是,在没有看到您的代码的情况下,您可能遇到与 JQuery 方法无关的瓶颈。

Using native functionality will generally be faster than an abstraction, such as JQuery.each() method. However, the JQuery.each() method is easier to use and requires less coding on your part.

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 might help, however, having not seen your code, it's possible you have bottlenecks unrelated to the JQuery method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文