querySelectorAll vs jQuery $() vs select()

JavaScript performance comparison

Test case created by Todd Henderson

Preparation code

<div id='fixture'> </div>
<div class='fixtureClass'> </div>
<ul id='fixtureList'>
<li class='fixtureListElement'></li>
<li class='fixtureListElement'></li>
<li class='fixtureListElement'></li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  /**
   * Returns a non-live NodeList of element objects from the given CSS selector.
   *
   * @param {string} selector -  A CSS selector to be queried.
   * @param {HTMLElement} [scope=document] - Scope for query.
   * @returns {HTMLElement[]} Returns a non-live array of HTMLElement.
   * @public
   */
  
  function select(selector, scope) {
    /**
     * Selector scope
     *
     * @type {HTMLElement}
     * @private
     */
    var _scope = scope || document;
  
    if (selector.indexOf("#") === 0 && selector.indexOf(" ") === -1 && selector.indexOf(".") === -1) {
  
      return [_scope.getElementById(selector.slice(1))];
  
    } else if (selector.indexOf(".") === 0 && selector.indexOf("#") === -1 && selector.indexOf(":") === -1) {
  
      return [].slice.call(_scope.getElementsByClassName(selector.replace(/./g, " ")));
    }
  
    return [].slice.call(_scope.querySelectorAll(selector));
  }

};
</script>

Preparation code output

<div id='fixture'> </div> <div class='fixtureClass'> </div> <ul id='fixtureList'> <li class='fixtureListElement'></li> <li class='fixtureListElement'></li> <li class='fixtureListElement'></li> </ul>

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('#fixture')
var div = select('#fixture');
pending…
select('.fixtureClass')
var div = select('.fixtureClass');
pending…
select('.fixtureListElement')
var div = select('.fixtureListElement');
pending…
document.querySelector('.fixtureListElement')
var div = document.querySelector('.fixtureListElement');
pending…
$('#fixture')
var div = $('#fixture');
pending…
$('.fixtureClass')
var div = $('.fixtureClass');
pending…
$('.fixtureListElement')
var div = $('.fixtureListElement');
pending…
document.querySelector('#fixture')
var div = document.querySelector('#fixture');
pending…
document.querySelector('.fixtureClass')
var div = document.querySelector('.fixtureClass');
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