querySelector vs querySelectorAll vs getElementById vs getElementsByClassName vs getElementsByTagName vs switch by RegExp test

JavaScript performance comparison

Revision 57 of this test case created by

Preparation code

<section>
<span></span>
<div>
  <div>
    <div>
<p id="foo" class="foo">
  bar
</p>
    </div>
  </div>
</div>
</section>


<script>
var fastQSA = (function() {
  var reID = /^#[^\s]+$/,
      reTagSimple = /^\w+$/,
      reClassSimple = /^\.[\w-]+$/;  
  return function fastQSA(sel) {
    var ctx = document;

    if (reID.test(sel)) {
      return ctx.getElementById(sel.substr(1));
    } else if (reTagSimple.test(sel)) {
      return ctx.getElementsByTagName(sel);
    } else if (reClassSimple.test(sel)) {
      return ctx.getElementsByClassName(sel.substr(1));
    } else {
      return ctx.querySelectorAll(sel);
    }
  };
})(); // var fastQSA = (function() {
</script>

    

Preparation code output

<section> <span></span> <div> <div> <div> <p id="foo" class="foo"> bar </p> </div> </div> </div> </section>

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
querySelector
document.querySelector("#foo");
pending…
querySelectorAll
document.querySelectorAll("#foo")[0];
pending…
getElementById
document.getElementById("foo");
pending…
getElementsByClassName
document.getElementsByClassName("foo")[0];
pending…
getElementsByTagName
document.getElementsByTagName("p")[0];
pending…
fastQSA(id)
fastQSA('#foo');
pending…
fastQSA(tag)
fastQSA('p')[0];
pending…
fastQSA(class)
fastQSA('.foo')[0];
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

bar