Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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').

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top