Reputation: 407
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:
(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?
Upvotes: 0
Views: 115
Reputation: 33769
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.
Upvotes: 1