Is there a significant difference if I construct a jQuery object around an element once or many times? For instance:
var jEl = $(el);
$.each(myArray, function() {
jEl.addClass(this);
}
versus:
$.each(myArray, function() {
$(el).addClass(this);
}
I know there are other ways to write this that might sidestep the issue, but my question is about whether I should work to do $(el) just once, or if it truly is irrelevant. The example is contrived.
Bonus points for explaining just what $(el) does behind the scenes.
I know that theoretically more work is being done, what I don't know is whether it matters... if jQuery caches it or the browsers are all really good at the second request or whatever, than its not worth it.
FYI: The relevant jQuery API link is here (which I provide because $() isn't the easiest thing to Google for): http://api.jquery.com/jQuery/#using-dom-elements
Also worth including this useful link: http://www.artzstudio.com/2009/04/jquery-performance-rules/, where several of his points center around saving, chaining, and selecting well.
Yes, there is a performance impact.
In the first example, only one instance is created.
In the second, an instance will be created for each iteration of the loop.
Depending on the size of myArray
, that could lead to a lot of extraneous instances being created which will chew through memory.
The first way will be faster. First of all you are creating a new object each time also it will depend on your browser, your page and what el is.
If el is a string (for example "#myname") then $(el)
will "query" the DOM to find that element. jQuery is quite fast in doing queries but it does take some time. So doing this many times will take that many times longer.
Do I get the bonus points?
Yes there will be. Each time $() is called, jQuery does a separate search of the DOM for the element.
If each search takes 0.1 seconds (usually much much faster, but it's an easy number to work with), and you've got 1000 elements in your array, that's 100 seconds devoted just to traversing the DOM in the second example, as opposed to just 0.1 seconds in the first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With