Search code examples
jqueryperformancejquery-selectorsmemory-efficient

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?


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.