Caching jQuery Objects (v25)

Revision 25 of this benchmark created by Shawn Terry on


Description

This test compares the performance impact of three different jQuery scenarios:

1) Multiple selectors, multiple statements 2) Cached selector, multiple statements 3) Cached selector, chained statements

The goal is to identify the best way to handle jQuery selectors for optimum performance.

Preparation HTML

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

<!--Sample DOM-->
<header>
<h1>Sample DOM</h1>
</header>
<nav>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
<div id="main">
  <div id="content">
  <div id="myDiv" class="myClass">
  <p>Sample content of non-consequence</p>
  </div>
  </div>
</div>
<footer>
<a href="#">Terms</a>
</footer>

Test runner

Ready to run.

Testing in
TestOps/sec
No Caching
$("#myDiv").css({'color':'red','opacity':'1','display':'block'});
$("#myDiv").attr('data-testcase','No caching');
$("#myDiv").removeClass('doesNotExist').addClass('doesNotExist');
ready
Object Caching
var jqoMyDiv = $("#myDiv");
jqoMyDiv.css({'color':'red','opacity':'1','display':'block'});
jqoMyDiv.attr('data-testcase','Use caching');
jqoMyDiv.removeClass('doesNotExist').addClass('doesNotExist');
ready
Object Caching + Chaining
var jqoMyDiv = $("#myDiv");
jqoMyDiv.css({'color':'red','opacity':'1','display':'block'}).attr('data-testcase','Use caching and chaining').removeClass('doesNotExist').addClass('doesNotExist');
ready

Revisions

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