views:

66

answers:

5

Is there any obvious advantage in performance in writing

var e = $("#el");

e.css(...);
e.attr(...);
....
e.click(...);

instead of

$("#el").css(...);
$("#el").attr(...);
....
$("#el").click(...);

?

A: 

Yes, the first one will have better performance, since jQuery only has to parse the selector and create a node set once. Of course, the difference may not be noticeable.

Matthew Flaschen
A: 

In performance, not enough to tell. In readability? Very obvious advantage

d2burke
+10  A: 

Yes, in the first version you're not finding the element again each time, which always has some cost. There's also a third option, chaining:

$("#el").css(...)
        .attr(...)
        .click(...);

This is the more common approach you'll see, but the styles vary per developer...the library was designed with chaining in mind. In your specific case of an ID selector, the cost of document.getElementById() is very minimal, with any other selector it adds up much more quickly.

Nick Craver
@Nick - I assume the cost would be much more significant when using a class selector, rather than an id? I tend to almost always store the jQuery object in a variable before performing any actions on it.
Marko
@Marko - Yes, pretty much any other selector aside from `$(document)`, `$(document.body)` and such will be *way* more expensive than an ID selector. I prefer chaining (when it's readable) but like the answer says...it varies per developer (or team) and that's perfectly alright, as long as it works for you and your team, run with it :)
Nick Craver
+1  A: 

Yes. Moreover, you get better readability (especially if you name things with what they are):

var $commentForm = $('#comment-form');
glebm
+1  A: 

If by obvious advantages you mean obvious to the user in this instance ... then probably not, as no one is complaining right now. If on the other hand, if you mean obvious advantages over the lifecycle of your code (and in the life-span of those who must maintain it [yourself included]) then the first has quite an advantage. First, it's faster to run as the equivalent non-jQuery code is:
(25% faster with Chrome 7.0.517.5 on Windows XP. See this test I created on jsperf.com)

var e = document.getElementById("el");
// do stuff with e

versus

document.getElementById("el").//manage the css
document.getElementById("el").//add, alter, or access attributes
document.getElementById("el").onclick // do something with this event.

Second, it's much more readable, as glebm has pointed out. If you use descriptive variable names -- which makes it faster to comprehend and edit later.

Sean Vieira