People here often suggest to cache the jQuery object created from a DOM element, like with this code:
$('#container input').each(function() {
$(this).addClass('fooClass');
$(this).attr('data-bar', "bar");
$(this).css('background-color', 'red');
});
- Does caching the jQuery object really improve the performance of our code?
- What happens “behind the scenes” when you pass a DOM element to the jQuery constructor?
In the jQuery tag info this warning appears:
Well… that is true only for string selectors, which get parsed with regex to find out what they are:
Then if the string is a selector (other than
id), jQuery traverses the DOM to find a match with its expensivefindfunction:So yes it’s expensive, but that is only true for selectors!
If we pass a
DOMElement, the only action jQuery does is saving the DOMElement parameter as the context of the newly created jQuery object and setting the length of the context to 1:I did some tests with jsPerf, and I found that indeed caching the jQuery object has only a little effect:
In Chrome it’s only 7% slower. (In IE it’s a little bit more significant: 12%.)