DOM Caching

JavaScript performance comparison

Revision 4 of this test case created by Romu

Preparation code

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

<div id="container">
   <ul>
       <li>list</li>
       <li>
         <ul>
             <li class="nested">nested 1</li>
             <li class="nested">nested 2</li>
             <li class="nested">nested 3</li>
         </ul>
       </li>
       <li>list</li>
       <li>list</li>
       <li>list</li>
   </ul>
   <div id="status"></div>
</div>
      
<script>
Benchmark.prototype.setup = function() {
  MY_OBJECT = 
  {
      cache: {},
  
      init: function()
      {
          this.cache.c = $('#container');
          this.cache.n = this.cache.c.find('.nested');
          this.cache.s = this.cache.c.find('#status');
          window.$c = $('#container');
          window.$nested = window.$c.find('.nested');
          window.DOMstatus = document.getElementById('status');
  
      }
  }
  
  MY_OBJECT.init();

};
</script>

Preparation code output

<div id="container"> <ul> <li>list</li> <li> <ul> <li class="nested">nested 1</li> <li class="nested">nested 2</li> <li class="nested">nested 3</li> </ul> </li> <li>list</li> <li>list</li> <li>list</li> </ul> <div id="status"></div> </div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
1a - no cache container find
//no cache container find
$.each($('#container').find('li'), function(i,v)
{
    //...
});
pending…
1b - cache container find
//cache container find
$.each(MY_OBJECT.cache.c.find('li'), function(i,v)
{
    //...
});
pending…
2a - no cache class elements loop
//no cache class elements loop
$.each($('.nested'), function(i,v)
{
    //...
});
pending…
2b - cache class elements loop
//cache class elements loop
$.each(MY_OBJECT.cache.n, function(i,v)
{
    //...
});
pending…
3a - no cache update status
//no cache update status
$('.nested').each(function(i,v)
{
    $('#status').text($(this).text());
});
pending…
3b - cache update status
//cache update status
$.each(MY_OBJECT.cache.n, function(i,v)
{
    MY_OBJECT.cache.s.text($(this).text());
});
pending…
3a - var cache update status
//no cache update status
$.each($nested, function(i,v)
{
    DOMstatus.innerText = this.innerText;
});
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.

0 Comments