jQuery object: to cache or not to cache?

Viewed 3549

I have some trouble that comes from my Javascript (JS) codes, since I sometimes need to access the same DOM elements more than once in the same function. Some reasoning is also provided here.

From the point of view of the performance, is it better to create a jQuery object once and then cache it or is it better to create the same jQuery object at will? Example:

function(){
  $('selector XXX').doSomething(); //first call
  $('selector XXX').doSomething(); //second call
  ...
  $('selector XXX').doSomething(); // n-th call
}

or

function(){
  var  obj = $('selector XXX');
  obj.doSomething(); //first call
  obj.doSomething(); //second call
  ...
  obj.doSomething(); // n-th call       
}

I suppose that the answer probably depends by the value of "n", so assume that n is a "small" number (e.g. 3), then a medium number (e.g. 10) and finally a large one (e.g. 30, like if the object is used for comparison in a for cycle).

Thanks in advance.

6 Answers
Related