querySelectorAll vs Custom Query Method

JavaScript performance comparison

Revision 14 of this test case created by

Preparation code

<script>

function Y(f) {
    return (function(h) {
        return h(h);
    })(function(h) {
        return f(function() {
            return h(h).apply(this, arguments);
        });
    });
}

var doc = this.document,
	getElementById = doc.getElementById,
	getElementsByClassName = doc.getElementsByClassName,
	getElementsByTagName = doc.getElementsByTagName,
	querySelectorAll = doc.querySelectorAll;

function select(selectors, context) {
context = context || doc;
	var selectors = selectors.split(',');
	return _selects(selectors, context);
}

function _selects(selectors, context) {
 context = context || doc;
	var elements = [],
		selector = selectors.shift();

	if(selectors.length === 0) {
		var nodeList = _select(selector, context);
		return elements.push(nodeList);
	}
	return _selects(selectors, context);
}

var simpleRe = /^(#?[\w-]+|\.[\w-.]+)$/, 
    slice = [].slice;

function _select(selector, context) {
context = context || doc;
    if(simpleRe.test(selector)) {
        switch(selector[0]) {
            case '#':
                return [getElementById.call(context, selector.slice(1))];
            case '.':
                return slice.call(getElementsByClassName.call(context, selector.slice(1)));
            default:
                return slice.call(getElementsByTagName.call(context, selector));
		}
    }
    return slice.call(querySelectorAll.call(context, selector));
}

function Ymem(F, cache) {
	if (!cache)
		cache = {} ; // Create a new cache.
	
	return function(arg) {
		if (cache[arg])
			return cache[arg] ; // Answer in cache.
  
		var answer = (F(function(n){
			return (Ymem(F,cache))(n);}))(arg); // Compute the answer.
  
		cache[arg] = answer ; // Cache the answer.
		return answer ;
	};
}
</script>
<div id="iddiv">
  <div class="inside"></div>
  <div class="inside"></div>
</div>
<div class="classdiv"></div>
    

Preparation code output

<div id="iddiv"> <div class="inside"></div> <div class="inside"></div> </div> <div class="classdiv"></div>

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
querySelectorAll
document.querySelectorAll('#iddiv');
document.querySelectorAll('.classdiv');
document.querySelectorAll('div .inside');
pending…
select
select('#iddiv, .classdiv, div .inside');
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