I am using jQuery 1.7.1
I am trying to write this code for readability as well as performance. In the two cases below, which one would perform better and why?
// BLOCK ONE
var DivHeight = 0;
$(".PC_SeriesDiv").each(function() {
var ThisDivHeight = $(this).height();
if (ThisDivHeight > DivHeight) {
DivHeight = ThisDivHeight;
}
});
DivHeight = DivHeight + "px";
$(".PC_SeriesDiv").animate({height: DivHeight}, 250);
// BLOCK TWO
var DivHeight = 0;
var PC_SeriesDiv = $(".PC_SeriesDiv");
PC_SeriesDiv.each(function() {
var ThisDivHeight = $(this).height();
if (ThisDivHeight > DivHeight) {
DivHeight = ThisDivHeight;
}
});
DivHeight = DivHeight + "px";
PC_SeriesDiv.animate({height: DivHeight}, 250);
My question really boils down to whether there is any benefit in doing this:
var PC_SeriesDiv = $(".PC_SeriesDiv");
Suggestions would be greatly appreciated. Thanks!
Yes, keeping a reference to the jQuery collection is a performance boost. Reference.
It has become customary to prefix saved jQuery collections with a
$, so you could do:Also, if all the elements in the HTML with a class of
PC_SeriesDivare the same type (ie,<div>s), it is more efficient to make the selector be$("div.PC_SeriesDiv");