getElementById VS jQuery('#id')

JavaScript performance comparison

Revision 113 of this test case created by Oleksandr Kelepko

Preparation code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script>
var MAX = 1000;
var elements = {};
for(var i = 0; i < MAX; ++i){
  var $el = $('<p id="foo' + i + '">Test</p>').appendTo($(document.body));
  elements['foo' + i] = $el[0];
}

var c = 0;
var next = function(){
  c++;
  if(c === MAX) c = 0;
  return 'foo' + c;
}
</script>
<script>
Benchmark.prototype.setup = function() {
    c = 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
getElById
document.getElementById(next());
pending…
jQuery
$('#' + next());
pending…
jQuery with getElById
$(document.getElementById(next()));
pending…
getElById -
document.getElementById('missing'+next())
pending…
jQuery -
$('#missing'+next())
pending…
indexed
elements[next()]
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