est
est

Reputation: 13

Performance: Which of these examples of code is faster and why?

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

or

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

Upvotes: 1

Views: 258

Answers (6)

Andreas Grabner
Andreas Grabner

Reputation: 156

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.

Upvotes: 1

Yacoby
Yacoby

Reputation: 55445

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();

Upvotes: 10

john Griffiths
john Griffiths

Reputation: 247

Juste fore funne

\Indifferent:

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

Upvotes: 0

Rich Bradshaw
Rich Bradshaw

Reputation: 72975

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.

Upvotes: 1

Martin K.
Martin K.

Reputation: 4703

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

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

Upvotes: 0

theomega
theomega

Reputation: 32031

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?

Upvotes: 0

Related Questions