jQuery $( 'selector' ) vs custom $( 'selector' )

JavaScript performance comparison

Test case created by ThinkingStiff

Preparation code

<section>
<div><div><div><div><div id="end" class="end"><div><div><div><div><div><div><div><div>
<article>
<p>
<span id="start" class="start"></span>
</p>
</article>
</div></div></div></div></div></div></div></div></div></div></div></div></div>
</section>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    function $2( selector ) {
   
        switch( selector[0] ) {
   
            case '#':
   
                return document.getElementById( selector.substring( 1 ) );
   
            case '.':
   
                return document.getElementsByClassName( selector.substring( 1 ) );
   
            case '<':
   
                var div = document.createElement( 'div' );
                div.innerHTML = selector;
                return div.childNodes.length == 1 ? div.childNodes[0] : div.childNodes ;
   
            default: //tags
   
                return document.getElementsByTagName( selector.substring( 1 ) );
   
        };
   
    };
   
};
</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
jQuery $( 'selector' )
var element = $( '#start' );
element = $( '#not-found' );
element = $( '.start' );
element = $( '.not-found' );
element = $( 'span' );
element = $( 'aside' ); //not found
element = $( '<div><span>hello</span></div>' );
 
pending…
custom $( 'selector' )
var element = $2( '#start' );
element = $2( '#not-found' );
element = $2( '.start' );
element = $2( '.not-found' );
element = $2( 'span' );
element = $2( 'aside' ); //not found
element = $2( '<div><span>hello</span></div>' );
 
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