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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
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:
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.
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 article (#3) ran some performance tests and found that the jQuery .each function was about 10x as slow as the native javascript for loop.
This method should give you a dramatic speed improvement.
Caching will also improve performance.
In use: