querySelectorAll vs getElementsByTagName and hasAttribute

JavaScript performance comparison

Test case created by Steven Benisek

Preparation code

<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="">
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="">
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="" data-picture>
<img src="http://placehold.it/150x150" alt="">
<script>
Benchmark.prototype.setup = function() {
    function hasAttribute(el, attr) {
      return el.getAttribute(attr) != null;
    }
   
    function getElementsByAttributeName(tag, attr, native) {
      var els = document.getElementsByTagName(tag),
          len = els.length,
          el, result = [],
          native = native || false;
   
      while (len--) {
        el = els[len];
        (native ? el.hasAttribute(attr) : hasAttribute(el, attr)) && result.push(el);
      }
   
      return result;
    }
};
</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 elements = document.querySelectorAll('[data-picture]');
pending…
getElementsByTagName + hasAttribute
var elements = getElementsByAttributeName('img', 'data-picture');
pending…
getElementsByTagName + native hasAttribute
var elements = getElementsByAttributeName('img', 'data-picture', true);
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

Add a comment