querySelectorAll vs getElementsByTagName vs Hybrid

JavaScript performance comparison

Revision 30 of this test case created by Philip Tellis

Info

Compare document.querySelectorAll vs document.getElementsByTagName vs a hybrid approach that uses the one fastest in the given browser.

Looks at all elements and pulls out its length to force getElementsByTagName to dereference the live nodeList.

Preparation code

<div>
  <ul>
    <li><a href="#">item 1</a></li>
    <li><a href="#">item 2</a></li>
    <li><a href="#">item 3</a></li>
  </ul>
</div>
<form>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</form>
<div>
<p>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
</p>
<p>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
<strong><em><span><a href="#"></a></span></em></strong>
</p>
</div>
<script>
Benchmark.prototype.setup = function() {
    var f=(/Opera/.test(navigator.userAgent)?document.querySelectorAll:document.getElementsByTagName);
};
</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
querySelectorAll
var nodes = document.querySelectorAll('*'),
nodelength = nodes.length;
pending…
getElementsByTagName
var nodes = document.getElementsByTagName('*'),
nodelength = nodes.length;
pending…
hybrid
var nodes = f.call(document, '*'),
nodelength = nodes.length;
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. Here’s a list of current revisions for this page:

0 comments

Add a comment