getElementById VS jQuery('#id')

JavaScript performance comparison

Revision 38 of this test case created by aaronlks

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<p id="foo">
  Test
</p>
<script>
  var wrap = function(id) {
      return $(document.getElementById(id))
      };
  var wrap2 = (function(window) {
    var doc = window.document;
    var jq = window.jQuery.fn.init;
    return function(id) {
      return new jq(doc.getElementById(id));
    };
  })(this);
</script>
<script>
Benchmark.prototype.setup = function() {
    var $el;
};

Benchmark.prototype.teardown = function() {
    $el[0].id = "foo";
};
</script>

Preparation code output

Test

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
getElementById
$el = $(document.getElementById('foo'));
pending…
jQuery
$el = $('#foo');
pending…
wrap
$el = wrap('foo')
pending…
wrap2
$el = wrap2('foo')
pending…
unwrap2
$el = new jQuery.fn.init(document.getElementById('foo'));
pending…
window.document.getElementbyID
$el = $(window.document.getElementById('foo'));
pending…
unwrap2 + window
$el = new jQuery.fn.init(window.document.getElementById('foo'));
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:

1 comment

aaronlks commented :

Had to test the slight variations. hmm

Add a comment