title: Caching jquery selector results using underscore memoize
body: <p>I'm looking into ways to optimize my Single Page Application, and I'm currently focusing on jQuery selectors.</p>
  
  <p>I'm no javascript expert, but it's my understanding that it's much more performant to store the results of a jquery selector in a variable for re-use, as opposed to re-querying the dom.</p>
  
  <p>So, for example, instead of this:</p>
  
  <pre><code>$("#myItem").doSomething();
  $("#myItem").doSomethingElse();
  </code></pre>
  
  <p>It makes more sense to do this:</p>
  
  <pre><code>var result = $("#myItem");
  result.doSomething();
  result.doSomethingElse();
  </code></pre>
  
  <p>Also, it's my understanding there can be great performance benefits for using the find() selector attached to an existing jQuery object as to reduce the amount of querying necessary:</p>
  
  <pre><code>$("#myItem").find(".highlighted");
  </code></pre>
  
  <p>I am interested in exploring the possibility of storing many of the selectors that we constantly reuse in our application not just in a local variable, but possibly in a hash somewhere, or an external function. I don't know if this would optimal, but I'm curious to what responses this receives.</p>
  
  <p>I've attempted (unsuccessfully) to use Underscore.js' memoize function to perform this, but it isn't working the way I expected. But, the concept will look like this:</p>
  
  <pre><code>   jquerySelect = function () {
                  var elements = _.memoize(function (selection) {
                      return $(selection);
                  });
                  return elements;
              };
  </code></pre>
  
  <p>The idea here being that the actual result work of the "return $(selection)" be performed once, after which the result is cached and returned.</p>
  
  <p>I'd like to be able to use this in the following way:</p>
  
  <pre><code>utils.jquerySelect(".highlighted").find("span")
  </code></pre>
  
  <p>In this simple example, the key to the cache is the ".highlighted", and the utility function knows how to access the result, thus saving the work of traversing the DOM from being done again. My implementation doesn't work currently, as the "return" statement is hit every time.</p>
  
  <p>I'm not sure if this approach is flawed, but I sense it may be. However, please let me know if you see a way for this to work, or if you see a better way of doing this.</p>