我应该使用 jQuery.each() 吗? [英] Should I use jQuery.each()?

查看:34
本文介绍了我应该使用 jQuery.each() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

jQuery 的每个源代码如下(感谢 John Resig 和 MIT License):

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

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

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.

这是因为意识到选择器开销已经发生并且您得到了一个填充数组 object.

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

这篇关于我应该使用 jQuery.each() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆