custom closestById()

JavaScript performance comparison

Test case created by ThinkingStiff

Info

Replacement for jQuery .closest() function.

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.7.1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var start = document.getElementById( 'start' );
   
        Element.prototype.closestById1 = function( id )
        {
           
            if( this.parentNode.nodeType == Node.ELEMENT_NODE )
            {        
               
                return this.getAttribute( 'id' ) == id
                    ? this
                    : this.parentNode.closestById1( id );
               
            };
           
        };
   
    Element.prototype.closestById2 = function( id ) {
       
        return ( this.id && this.id == id )
            ? this
            : ( this.parentNode.closestById2 && this.parentNode.closestById2( id ) );
       
    };
   
   
    Element.prototype.closestById3 = function( id ) {
       
        if( this.id && this.id == id ) {
           
            return this;
           
        } else {
         
            return this.parentNode.closestById3 && this.parentNode.closestById3( 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
closestById1
var element = start.closestById1( 'start' ),
    element = start.closestById1( 'end' ),
    element = start.closestById1( 'not-found' );
 
pending…
closestById2
var element = start.closestById2( 'start' ),
    element = start.closestById2( 'end' ),
    element = start.closestById2( 'not-found' );
 
pending…
closestById3
var element = start.closestById3( 'start' ),
    element = start.closestById3( 'end' ),
    element = start.closestById3( 'not-found' );
 
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