jQuery .closest( '#id' ) vs DOM Element.closestById( 'id' )

JavaScript performance comparison

Test case created by ThinkingStiff

Preparation code

<section>
<div><div><div><div><div id="end"><div><div><div><div><div><div><div><div>
<article>
<p>
<span id="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.6.4/jquery.min.js"></script>

 
<script>
Benchmark.prototype.setup = function() {
    var startJQ = $( '#start' ),
        startDOM = $( '#start' )[0];
   
    Element.prototype.closestById = function( id )
    {
       
        if( this.parentNode.nodeType == Node.ELEMENT_NODE )
        {        
           
            return this.getAttribute( 'id' ) == id
                ? this
                : this.parentNode.closestById( id );
           
        };
       
    };
};
</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
.closest( '#id' )
var jq1 = startJQ.closest( '#end' ),
    jq2 = startJQ.closest( '#not-found' );
 
pending…
.closestById( 'id' )
var dom1 = startDOM.closestById( 'end' ),
    dom2 = startDOM.closestById( 'not-found' );
 
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. Here’s a list of current revisions for this page:

0 comments

Add a comment