JQuery $('#id') selector vs $([id='id'])

JavaScript performance comparison

Revision 29 of this test case created

Info

Fastest way get a jQuery object of a DOM element of which I have the ID. # selector has the advantage of using the native getElementById method under the covers while the attribute selector must traverse both the dom and the attributes of the dom element.

Preparation code

<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 = "i" + S4();
    jid = '#' + did;
    aid = '[id="' + did +'"]';
};
</script>

Preparation code output

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…
jQuery('[id=id]')
jQuery(aid);
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