Search code examples
javascriptjqueryoverhead

repeat $() all over the place or declare once and reuse?


Using jQuery, if I am writing code like this

$('blah').doSomething(); 
//bunch of code
$('blah').doSomethingElse();
//bunch of code
$('blah').doOtherStuff();

Is a new jQuery object being created each time I say $('blah') ?

If so, would it reduce object creation overhead to do something like this instead:

var blah = $('blah');
blah.doSomething(); 
//bunch of code
blah.doSomethingElse();
//bunch of code
blah.doOtherStuff();

Make sense?


Solution

  • Absolutely correct!

    Why Cache

    Another benefit of caching is code maintainability. If the selector is only in one place, changing it only needs to be done in one place. Trust me that makes life easier when maintaining code.

    Chain

    Although you can go one step further (where relevant), and chain your calls:

    $('blah')
    .doSomething()
    .doSomethingElse()
    .doOtherStuff();
    

    This is slightly better for 2 reasons. Firstly, you're not using the extra variable, so you save a tiny amount of memory. Secondly, the language doesn't perform lookups for each identifier use, so it's quicker.

    So, why do people still [over]use $()

    One reason people use lots of $() is because they don't know any better.

    Another reason is because element selection used to be slower. But as with most things in the browser, querying objects with selectors is fast being optimised (document.querySelectorAll), which means it's not such a big deal to cache or not to cache, so maybe with that in mind they allow themselves not to cache.

    Finally, there are benchmarks hanging around (one two from a quick google) that try to claim that it doesn't matter or is maybe even faster not to cache. The problem with most of these benchmarks and why I suggest you be very wary about drawing conclusions from them, is that the DOM in the example is not real-world; it's overly simplistic. Secondly, the selectors are simplistic as well. So of course querying will be lightning fast and caching won't make a big difference, but I don't find them at all conclusive.

    That said, if your example is similar to those of the benchmarks, then maybe you can draw your own circumstantial conclusions, and caching might just be a nuisance.