$("#id") vs $(document.getElementById)

JavaScript performance comparison

Revision 9 of this test case created by Kyle Simpson

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<div id="LOL"></div>
<script>
  var $el = $(0);
</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
#id
$("#LOL");
pending…
native
$(document.getElementById("LOL"));
pending…
Sizzle
$("[id=LOL]");
pending…
common mistake
$('div#LOL');
pending…
native queryselectorall
$(document.querySelectorAll('#LOL'))
pending…
native queryselector
$(document.querySelector('#LOL'))
pending…
manual jquery collection
$el.context = $el[0] = document.getElementById("LOL")
// $el == $(document.getElementById("LOL"))
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:

2 comments

Alex Sexton commented :

A thing to note, is that not all of these are cross-browser safe. jQuery and other libraries have their own wrappers for querySelectorAll and getElementById because they are broken in some cases. Notably when forms have conflicting names.

How often is an id selector the bottleneck in your application?

Alexsandro commented :

Look, it's curious, Chrome with lot or opened tables around of 90 tabs and and 1,791,364k memory of RAM, manual jquery collection get only 540,221 against 708,232 from ID.

Chrome 7.0.536 10,832 50,785 708,232 540,221 583,198 244,608 76,366 1

Add a comment