我应该使用 jQuery.each() 吗?
我对对象数组进行非常频繁的迭代,并且一直在使用 jQuery.each()。但是,我遇到了速度和内存问题,根据我的分析器,最常调用的方法之一是 jQuery.each()。街上对其性能的评价如何?我应该切换到简单的 for 循环吗?当然,我也在解决我自己的代码中的许多问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
本文 (#3) 运行了一些性能测试,发现 jQuery .each 函数的速度大约是原生 javascript for 循环的 10 倍。
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.
jQuery 的每个源代码如下(感谢 John Resig 和 MIT 许可证):
正如您可以跟踪和看到的,在大多数情况下,它使用基本的 for 循环,其中唯一的开销实际上只是回调本身。不应该对性能产生影响。
编辑:这是因为意识到选择器开销已经发生,并且您得到了一个填充的数组
对象
。The source code for jQuery's each is as follows (Thank you John Resig and MIT License):
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
.这种方法应该可以显着提高速度。
缓存也将提高性能。
使用中:
This method should give you a dramatic speed improvement.
Caching will also improve performance.
In use:
确保充分利用 jquery 的一种方法是将返回的结果数组存储在变量中,而不是每次需要获取某些内容时都重新遍历 DOM。
不应该做什么的示例:
更好的做法:
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:
Better practice:
使用本机功能通常比抽象更快,例如 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.