views:

208

answers:

6
$('#element').method();

or

var element = $('#element');
element.method();
A: 

If you run only this code, no one should realy be faster. The second one might need more memory (because of the additional variable created).

If you want to be sure, why not test it yourself using a small selfwritten benchmark?

theomega
A: 

I think $('#element').method(); does not need as much memory as

var element = $('#element'); ... because you bind #element to a variable.

Martin K.
So the difference is only in memory consumption, not the speed... Regardless of the DOM size?
est
Binding an element will cost a couple of cycles, but the first probably has an implicit bind in most implementations in any case so there is probably absolutely no difference.The DOM size won't matter since you're binding a reference to the object, there is no copying involved. References are always the same size regardless of how big the DOM object is.
Tom
Yeah, that makes sense. Thanks.
est
+9  A: 

Without using a profiler, everyone is just guessing. I would suspect that the difference is so small it isn't worth worrying about. There are small costs to the second above the first like having to preform a lookup to find 'var element' to call the method on, but I would have thought finding '#element' and then calling the method is far more expensive.

However, if you then went on to do something else with element, the second would be faster

//Bad:
$('#element').foo();
$('#element').bar();

//Good:
var e = $('#element');
e.foo();
e.bar();
Yacoby
Almost all jQuery methods support chaining. The idiomatic form of this is $('#element').foo().bar().
George V. Reilly
I think he was showing running a function on the same selector set without caching is bad if you need to run the functions at different times.
Doug Neiner
+1  A: 

If you were using a loop where the value of $('#element') was used a lot, then caching it as in the 2nd version before the loop would help a lot.

For just this small snippet, it makes little difference.

Rich Bradshaw
A: 

Juste fore funne

\Indifferent:

$('#element').foo().bar();

john Griffiths
+1  A: 

Lookups via id (#) are pretty fast. I just tested your scenario on a small page with 2 div tags. Here is the code i used var x = $("#div1"); var y = $("#div2"); var z = $("#div1"); every lookup took about 0.3ms on my laptop. The 2nd lookup for div1 executed the same internal jQuery methods as the first - indicating that there is no caching of already looked up objects Performance becomes a bigger problem when you use other selectors like classname or more advanced jQuery selectors. I did some analysis on jQuery Selector Performance - check it out - hope it is helpful.

Andreas Grabner