Various ways of selecting elements

JavaScript performance comparison

Test case created by T.J. Crowder

Preparation code

<!-- Normally you don't want to do this, it returns something that can only be cached for a day. Normally you want to ask for a specific version, which can be cached for a year. But for a test like this it makes sense. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div>
    <div></div>
    <div class="foo"></div>
    <div></div>
    <div></div>
    <div class="foo"></div>
    <div></div>
    <div></div>
    <div class="foo"></div>
</div>
      
<script>
Benchmark.prototype.setup = function() {
  if (!Array.prototype.indexOf) {
      // NOT a real implementation, just enough for our test
      Array.prototype.indexOf = function(target, start) {
          var n;
          for (n = start || 0; n < this.length; ++n) {
              if (this[n] === target) {
                  return n;
              }
          }
          return -1;
      };
  }
  
  function timeWastedCoding(tag, cls) {
      var list = document.getElementsByTagName(tag);
      var rv = [];
      var n;
      var elm;
      for (n = 0; n < list.length; ++n) {
          elm = list[n];
          if (elm.className.split(" ").indexOf(cls) !== -1) {
              rv.push(elm);
          }
      }
      return rv;
  }
  
  function timeWastedCoding2(tag, clsRex) {
      var list = document.getElementsByTagName(tag);
      var rv = [];
      var n;
      var elm;
      for (n = 0; n < list.length; ++n) {
          elm = list[n];
          if (clsRex.test(elm.className)) {
              rv.push(elm);
          }
      }
      return rv;
  }

};
</script>

Preparation code output

<!-- Normally you don't want to do this, it returns something that can only be cached for a day. Normally you want to ask for a specific version, which can be cached for a year. But for a test like this it makes sense. --> <div> <div></div> <div class="foo"></div> <div></div> <div></div> <div class="foo"></div> <div></div> <div></div> <div class="foo"></div> </div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
jQuery
if ($("div.foo").length !== 3) throw "Error in test";
pending…
querySelectorAll
if (document.querySelectorAll("div.foo").length !== 3) throw "Error in test";
pending…
timeWastedCoding2
if (timeWastedCoding2("div", /\bfoo\b/).length !== 3) throw "Error in test";
pending…
timeWastedCoding
if (timeWastedCoding("div", "foo").length !== 3) throw "Error in test";
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