custom $( 'selector' ) vs getElementById

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>
Benchmark.prototype.setup = function() {
    function $( 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
custom $( 'selector' )
var element = $( '#start' );
pending…
getElementById()
var element = document.getElementById( 'start' );
 
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