querySelector vs querySelectorAll vs getElementById vs getElementsByClassName vs getElementsByTagName vs switch by RegExp test (v57)

Revision 57 of this benchmark created on


Description

  • Test the speed of various getElementXXX / querySelectorXXX method
  • also test it against a simple wrapper that is functionally the same as the general querySelectorAll(), but uses various faster getElementXXX methods by checking selector pattern using RegExp.

Preparation HTML

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


<script type="text/javascript">
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>

Test runner

Ready to run.

Testing in
TestOps/sec
querySelector
document.querySelector("#foo");
ready
querySelectorAll
document.querySelectorAll("#foo")[0];
ready
getElementById
document.getElementById("foo");
ready
getElementsByClassName
document.getElementsByClassName("foo")[0];
ready
getElementsByTagName
document.getElementsByTagName("p")[0];
ready
fastQSA(id)
fastQSA('#foo');
ready
fastQSA(tag)
fastQSA('p')[0];
ready
fastQSA(class)
fastQSA('.foo')[0];
ready

Revisions

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