Cached DOM Traversal VS New ID selection

JavaScript performance comparison

Test case created by Jason

Info

See this question: http://stackoverflow.com/questions/10424975/is-it-faster-to-traverse-the-dom-from-a-cached-selector-than-to-find-an-idd-ele

Preparation code

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

<div class="myclass" id="myid">
    <a href="javascript:">Click me!</a>
</div>
<script>
Benchmark.prototype.setup = function() {
    var link = $('a');
};
</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
Traverse .closest()
link.closest('.myclass');
pending…
Fresh ID
$('#myid');
pending…
Traverse .parent()
link.parent();
pending…
Traverse .parents()
link.parents('.myclass');
pending…
Fresh object from class
$('.myclass');
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