Caching jQuery Objects (with inefficient selectors)

JavaScript performance comparison

Revision 22 of this test case created


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

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

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

Preparation code

<script src=""></script>

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

Preparation code output

Sample DOM

Sample content of non-consequence

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
No Caching
$(".myClass .inner-div").css("color", "red");
$(".myClass .inner-div").css("opacity", 1);
$(".myClass .inner-div").css("display", "block");
Method Chaining
$(".myClass .inner-div").css("color", "red").css("opacity", 1).css("display", "block");
Object Caching
var $myDiv = $(".myClass .inner-div");
$myDiv.css("color", "red");
$myDiv.css("opacity", 1);
$myDiv.css("display", "block");
Object Caching + Chaining
var $myDiv = $(".myClass .inner-div");
$myDiv.css("color", "red").css("opacity", 1).css("display", "block");

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment