Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cache jQuery objects?

So why are we supposed to cache jQuery objects?

In the following scenario:

var foo = $('#bar');
foo.attr('style','cool');
foo.attr('width','123');

$('#bar').attr('style','cool'); $('#bar').attr('width','123');

Why is the first option so much better than the second option?

If it's because of performance, how does it reduce usage?

like image 608
ThePixelPony Avatar asked May 19 '14 17:05

ThePixelPony


1 Answers

Because the jQuery function has a lot of code in it, which involves unnecessary overhead if you execute it more than once with the same inputs expecting the same outputs. By caching the result, you store a reference to the exact element or set of elements you're looking for so you don't have to search the entire DOM again (even if it's a fairly fast search). In many cases (simple pages with small amounts of code) you won't notice a difference, but in the cases where you do it can become a big difference.

You can see this in action by testing your example in jsPerf.

You can also think of it as an example of the Introduce Explaining Variable refactoring pattern for readability purposes, particularly with more complex examples than the one in the question.

like image 182
David Avatar answered Oct 21 '22 12:10

David