Caching jQuery Objects

JavaScript performance comparison

Revision 4 of this test case created

Info

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="//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>
<script>
Benchmark.prototype.setup = function() {
    var myDiv = document.getElementById("myDiv");
    var myDivStyle = myDiv.style;
    var $myDiv = $("myDiv");
};
</script>

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
$myDiv.css("color","red");
$myDiv.css("opacity",1);
$myDiv.css("display","block");
pending…
Method Chaining
$myDiv.css("color","red").css("opacity",1).css("display","block");
pending…
All in one call
$myDiv.css({"color": "red", "opacity": 1, "display": "block"});
pending…
All in one call without strings
$myDiv.css({color: "red", opacity: 1, display: "block"});
pending…
No jQuery
myDiv.style.color = "red";
myDiv.style.opacity = 1;
myDiv.style.display = "block";
pending…
No jQuery (style cached)
myDivStyle.color = "red";
myDivStyle.opacity = 1;
myDivStyle.display = "block";
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