getElementById vs. querySelector

JavaScript performance comparison

Revision 224 of this test case created by

Preparation code

<p class="foo">Foo</p>
<p class="bar">Bar</p>
      
<script>
Benchmark.prototype.setup = function() {
  var idSelectorRegexp = /^#[a-zA-Z]+[a-zA-Z0-9_\-]*$/;
  
  var select = function(query){
    // pure ID selector?
    if (idSelectorRegexp.test(query))
      return document.getElementsByClassName(query.slice(1));
    else
      return document.querySelectorAll(query);
  };

};
</script>

Preparation code output

<p class="foo">Foo</p> <p class="bar">Bar</p>

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
getElementsByClassName
var bar = document.getElementsByClassName("bar");
pending…
querySelectorAll
var bar = document.querySelectorAll(".bar");
pending…
getElementsByTagName
var bar = document.getElementsByTagName("p");
pending…

Compare results of other browsers

Revisions

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

0 Comments

Foo

Bar