DOM traversing vs cached refference

JavaScript performance comparison

Test case created by Marcin Kierski

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div class="someClass">
  <ul>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li id="my-id" class="active">
      <a href=""></a>
    </li>
  </ul>
</div>
<script>
Benchmark.prototype.setup = function() {
    var cachedElement = document.getElementsByClassName('active')[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
cachedElement
var className = cachedElement.className;
pending…
DOM traversing by class name
var className = document.getElementsByClassName('active')[0].className;
pending…
DOM traversing by id
var className = document.getElementById('my-id').className;
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment