Why cache jQuery selectors?

Benchmark created by C. Spencer Beggs on


Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/sec
Cached
$(document).ready(function() {
  var foo = $("#bar");
  foo.attr("style", "color: black;");
  foo.attr("class", "foo");
});
ready
Not cached
$(document).ready(function() {
  $("#bar").attr("style", "color: black;");
  $("#bar").attr("class", "foo");
});
ready

Revisions

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