querySelectorAll vs getElementById

JavaScript performance comparison

Revision 87 of this test case created by Argomix

Preparation code

<p id="foo" class="cbar">bar</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
<script
			  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
			  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
			  crossorigin="anonymous"></script>

      
<script>
Benchmark.prototype.setup = function() {
  var S = function(query){
  let q = query[0];
  return (q === ".") ? document.getElementsByClassName(query.slice(1)) :
         (q === "#") ? document.getElementById(query.slice(1)) :
         document.querySelectorAll(query);
  };
  
  var X = function(query){
    let q = query[0];
    if (q === "."){
        return document.getElementsByClassName(query.slice(1));
    }else if (q === "#"){
    		return document.getElementById(query.slice(1));
    }else{
    		return document.querySelectorAll(query);
    }
  };

};
</script>

Preparation code output

<p id="foo" class="cbar">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
select
var result = S(".cbar");
pending…
querySelectorAll
var result = document.querySelectorAll('.cbar');
pending…
getElementsByClassName
var result = document.getElementsByClassName('cbar');
pending…
jQuery
var result = jQuery(".cbar");
pending…
Zepto
var result = Zepto(".cbar");
pending…
select2
var result = X(".cbar");
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