Evik James
Evik James

Reputation: 10483

Is there a performance advantage to coding this one way or another?

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!

Upvotes: 1

Views: 60

Answers (3)

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

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:

var $PC_SeriesDiv = $(".PC_SeriesDiv");

Also, if all the elements in the HTML with a class of PC_SeriesDiv are the same type (ie, <div>s), it is more efficient to make the selector be $("div.PC_SeriesDiv");

Upvotes: 2

Max
Max

Reputation: 41

Going with the second way (intermediate variable) gives you more flexibility in the future - if you ever change the name of the element, you would only need to change one place in the code that handles that. Performance-wise, I would highly doubt you could feel the difference - internally it's either substituted back as a reference or still very negligible. In fact, it might be faster because you would not need to do a lookup again.

Upvotes: 2

Mike K.
Mike K.

Reputation: 3789

Cacheing the value in PC_SeriesDiv is preferable as Block 1 would require JQuery to search the DOM twice, Block 2 is more efficient.

Upvotes: 2

Related Questions