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(...);
?
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(...);
?
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.
In performance, not enough to tell. In readability? Very obvious advantage
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.
Yes. Moreover, you get better readability (especially if you name things with what they are):
var $commentForm = $('#comment-form');
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.