Alex Guerin
Alex Guerin

Reputation: 2386

jQuery selector efficiency

I have a quick Bing and can't really find the answer.

If I have a whack of code that uses $('something here') 150 times, would it be more efficient to:

var item = $('something here')

Pretty silly questions I know, but would it be more efficent as jQuery only has to find the item once?

Upvotes: 1

Views: 597

Answers (3)

Vinayak Phal
Vinayak Phal

Reputation: 8919

Please go through this article to know exactly how jQuery is working behind the screen. Very well explained.

http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-jquery-newbs-stop-jumping-in-the-pool/

Upvotes: 1

dangerChihuahua007
dangerChihuahua007

Reputation: 20895

According to this article, it is more efficient to assign the selector to a variable, which makes sense since jQuery does not need to scan the DOM for elements matching the selector again.

http://geekswithblogs.net/renso/archive/2009/07/14/jquery-selector-efficiencycost-impact.aspx

It also provides other tips. For instance, try to avoid using the class selector alone. Interestingly, a selector such as $('#someID') is faster than $('div#someID').

Upvotes: 4

Jordan Mack
Jordan Mack

Reputation: 8723

Yes, storing the resulting jQuery object is tremendously more efficient and may be magnitudes faster. Each time you use a selector you are initiating a new search. jQuery does not cache results. If you store the resulting jQuery object in a variable, you are effectively eliminating the need to run the search over and over again each time.

Upvotes: 3

Related Questions