id vs find with id

JavaScript performance comparison

Test case created by heroin

Preparation code

<div id="foo">
            <h6>Element</h6>
            <div class="bar">Class</div>
            <div id="bar">Sub-ID</div>
            <input type="text" value="FooBar">
            <span id="hidden" style="display:none;">Hidden</span>
            <ul itemprop="list" id="ul" class="ul">
                <li class="li">One</li>
                <li class="li">Two</li>
                <li class="li">Three</li>
                <li class="li">Four</li>
                <li class="li">Five</li>
                <li class="li">Six</li>
            </ul>
        </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
   var testObj;
    
    (function($){
        var fooEl = $('#foo');
        testObj = {
            idTest		:   function ( test ) {
                switch ( test ) {
                    case 0:
                        return $('#bar');
                    case 1:
                        return $('#foo').find('#bar');
                    case 2:
                        return fooEl.find('#bar');
                    default:
                        break;
                }
            }
        };
    })(jQuery);

};
</script>

Preparation code output

<div id="foo"> <h6>Element</h6> <div class="bar">Class</div> <div id="bar">Sub-ID</div> <input type="text" value="FooBar"> <span id="hidden" style="display:none;">Hidden</span> <ul itemprop="list" id="ul" class="ul"> <li class="li">One</li> <li class="li">Two</li> <li class="li">Three</li> <li class="li">Four</li> <li class="li">Five</li> <li class="li">Six</li> </ul> </div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
id
testObj.idTest(0); //$('#bar');
pending…
find with id
testObj.idTest(1); //$('#foo').find('#bar');
pending…
find with id by cached element
testObj.idTest(2); //fooEl.find('#bar');
pending…

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments

Element
Class
Sub-ID