jQuery dollar overwrite

JavaScript performance comparison

Test case created by Laurens

Info

jQuery selector overwrite as an attempt to get a better performance on simple selections

Preparation code

<div id="firstId">
  <div class="testClass">
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    if (!document.getElementsByClassName) {
      document.getElementsByClassName = function(cl, tag) {
        var els, matches = [],
            i = 0,
            len, regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
   
        els = document.getElementsByTagName(tag || "*");
        if (!els[0]) return false;
   
        for (els.length; i--;) {
          if (els[i].className.match(regex)) {
            matches.push(els[i]);
          }
        }
   
        return matches;
      };
    }
   
    S = (function($) {
      return function(el, tag) {
        if (typeof el === 'object') return $(el);
   
        //if (document.querySelectorAll) return document.querySelectorAll(el);
   
        var firstChar = el.charAt(0);
        var spaces = new RegExp('\s');
   
        if (!el.match(spaces)) {
          switch (firstChar) {
          case "#":
            return $(document.getElementById(el.slice(1)));
          case ".":
            return $(document.getElementsByClassName(el.slice(1), tag));
          default:
            return $(el);
          }
        }
   
        return $(el);
      }
    }($));
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery $ overwrite
var a = S('#firstId');
var b = S('.testClass');
var c = S('#firstId .testClass');
var d = S(document.getElementById('firstId'));
pending…
jQuery without $ overwrite
var a = $('#firstId');
var b = $('.testClass');
var c = $('#firstId .testClass');
var d = $(document.getElementById('firstId'));
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment