Question

I've read everywhere that variable caching and chaining jQuery function calls was good for performance.

However, I've come across this jsperf test that seems to demonstrate some interesting quirks.

Please see the below test cases:

Case 1: No Caching

$(".myClass").css("color", "red");
$(".myClass").css("opacity", 1);
$(".myClass").css("display", "block");

Case 2: Chaining

$(".myClass").css("color", "red").css("opacity", 1).css("display", "block");

Case 3: Object Caching

var $myDiv = $(".myDiv");
$myDiv.css("color", "red");
$myDiv.css("opacity", 1);
$myDiv.css("display", "block");

Case 4: Object Caching + Chaining

var $myDiv = $(".myClass");
$myDiv.css("color", "red").css("opacity", 1).css("display", "block");

Case 5: normal jQuery

$(".myClass").css({
  color: "red",
  opacity: 1,
  display: "block"
});

Here's the performance test results on my computer (Win7 FF18) ordered by test cases:

  1. No Caching - 7,284 ops/s - 92% slower, slowest
  2. Chaining - 10,284 ops/s - 89% slower
  3. Object Caching - 95,968 ops/s - fastest
  4. Object Caching + Chaining - 10,353 ops/s - 89% slower
  5. Normal jQuery - 10,172 ops/s - 89% slower

(These results are conform with measurements made with other browsers.)

As you can see, the test case 1 is the slowest which was expected. Oddly, the test case 3 is the fastest, while the test case 2, 4 and 5 are quite slow too.

The biggest surprise is that the test case 3 is much faster than test case 4. In other words, chaining jQuery calls greatly reduced performance.

Have you noticed this on your own browser?

Maybe it's a perk of the .css() method, but personally, I think that modern Javascript engines have already made special code optimisations to enhance sequences of function calls from the same root object.

What do you think?

Was it helpful?

Solution

The "Object Caching" test is so much faster because it's not actually doing anything.

It uses a different selector than the others: .myDiv instead of .myClass. There are no .myDiv elements, so the calls are acting on an empty result set.

If you fix that broken test, you get results more like what you'd expect: repeating the selector is still slowest, and the other 4 options are all more or less equivalent, speed-wise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top