With the first post of the year, I’d like to present the results of a (very) simple and unreliable performance benchmark.

The question I would like to give an answer to was: giving the selector of an HTML ID, how much the document.getElementById is faster than the jQuery selection? Well – as it tourned out – it is astonishingly faster.

The test run over 100000 calls to the same minimal function and then collect the result in millisecond. For each test, 8 runs were made and the greatest and lowest value were dropped before the average time was computed. Every test was ran against Firefox 3.5.6, Firefox 3.6b5, Chrome 4, Safari 4, IE 8 and Opera 10.10.

“Why don’t run the test also against the soon to be released jQuery 1.4.0?”, I asked myself. So I did.

The test code itself goes along these lines:

function benchmark(f, result) {
  var start = new Date();
  f();
  var stop = new Date();
  document.getElementById(result).innerHTML = stop - start;
}

$("#start").click(function() {
    benchmark(function() {
      var e;
      for(n=0; n < 100000; n++) {
        e = $('#testID');
// or  e = document.getElementById('#testID');
      }
    }, "result");
    return false;
});

And here comes the whole picture:

What did I learn?

  • when possible, use the document.getElementById() native function (or a simple helper wrapper) instead of the jQuery method
  • IE and Firefox 3.5 are embarassingly slow
  • Chrome and Safari are embarassingly fast
  • Firefox 3.6 is gaining a lot of performance points, but still…
  • Opera 10.10 is good, but the gEBI performances are very bad
  • Chrome is loosing something with jQuery 1.4. Well, it seems so. I don’t think this is real.
  • The best performance gain with jQuery 1.4 would be for IE8

Remember that this test is extremely unreliable and of indicative quality only. Do not take any assumption for granted :)

ADDENDUM: as a follow up to a discussion on Friendfeed, I ran one more test. This time I’ve used a wrapper like this one:


function $getId(id) {
  $(document.getElementById(id));
}

$("#startWRAPPER").click(function() {
    benchmark(function() {
      var e;
      for(n=0; n < 100000; n++) {
        e = $getId('testID');
      }
    }, "result");
    return false;
});

When you need an ID, as a jQuery object, using the wrapper can certainly give you same benefits. The test has been ran with the latest jQuery 1.4 version.

Print