title: (Why) Is it faster to use a jQuery-like selector & execute one of its methods, rather than look up a named function?
body: <p>I was wondering if defining some 'shorthand' functions in your own native JS code is faster than using jQuery (or any other library which returns an object). For example, suppose I would want to add a class to an element.</p>
  
  <p>In jQuery I would do:
  </p>
  
  <pre><code>$('#sammpleDiv').addClass('someClass');
  </code></pre>
  
  <p>And in native JS I could do:
  </p>
  
  <pre><code>// for simplicity's sake, the toElem parameter can only be an id
  function addClass(toElem, classToAdd) {
    document.getElementById(toElem).className += ' ' + classToAdd;
  };
  addClass('sampleDiv','someClass');
  </code></pre>
  
  <p><strong>EDIT: These are the correct jsPerfs <a href="http://jsperf.com/jquery-methods-or-js-functions/5" rel="nofollow">with simple replace</a> &amp; <a href="http://jsperf.com/jquery-methods-or-js-functions/8" rel="nofollow">with classList</a> that answer this question</strong></p>
  
  <p>What's faster? According to a <a href="http://jsperf.com/jquery-methods-or-js-functions" rel="nofollow">jsPerf I made</a>, the native JS implementation was more than 100% slower. </p>
  
  <p>So why is it faster to use <code>$</code> and return a new instance of <code>jQuery.fn.init</code> object, perform a bunch of find and filter tests and a lot of other operations (what jQuery does in effect), then execute one of its methods rather than look up a named function?</p>