JQuery $('#id') selector vs $(document.getElementById('id')

JavaScript performance comparison

Revision 30 of this test case created by NJH

Info

Fastest way get a jQuery object of a DOM element of which I have the ID. document.getElementById has the advantage of not requiring escaping for special characters.

Preparation code

<section>
        <hgroup>
                <h1>title</h1>
                <h2>subtitle</h2>
        </hgroup>
        <p>some text
        </p>
        <nav>
                <ul>
                        <li><a href="">links</a></li>
                        <li><a href="">links</a></li>
                        <li><a href="">links</a></li>
                </ul>
        </nav>
        <img src="" alt="" />
</section>
<div id="el">Some HTML element</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1/prototype.js"></script>

<script>
jQuery.noConflict();

var el = document.getElementById('el'), did='el', jid='#el';

function S4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
</script>
<script>
Benchmark.prototype.setup = function() {
    el.id = did = S4();
    jid = '#' + did;
    djid = 'div#' + did;
};
</script>

Preparation code output

title

subtitle

some text

Some HTML element

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery('#id')
jQuery(jid);
pending…
document.getElementById('id')
document.getElementById(did);
pending…
jQuery('div#id')
jQuery(djid);
pending…
jquery prototype
jQuery($(did));
pending…
doc jquery
jQuery(document.getElementById(did));
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