custom closestById()
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
closestById1 |
|
pending… |
closestById2 |
|
pending… |
closestById3 |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments