Is there a performance impact to using the jQuery $() operator many times?

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.

Answers


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.


Need Your Help

Toggle div with easing

jquery jquery-ui html toggle easing

I've got a link, when clicking this I want a div to slideIn with easing, and then clicking the link again, it should close the div, with easing...

How do I add an `.order` invocation to a ActiveRecord collection that I retrieved?

ruby-on-rails ruby-on-rails-3 rails-3.1

I am new in this world of Rails. And I cannot get my head around this problem. How to get @microposts ordered by the date the micropost was created.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.