Why you should care
Remediating this code pattern can take back up to 50% of the time consumed by a function.
Since object members may contain other members, it’s not uncommon to see patterns such as window.location.href in JavaScript code. These nested members cause the JavaScript engine to go through the object member resolution process each time a dot is encountered, while storing properties in local variables will dramatically increase execution speed in some cases.
CAST Recommendations
Generally speaking, if you’re going to read an object property more than one time in a function, it’s best to store that property value in a local variable. The local variable can then be used in place of the property to avoid the performance overhead of another property lookup. This is especially important when dealing with nested object members that have a more dramatic effect on execution speed.
Bad pattern:
function toggle(element){
if (YAHOO.util.Dom.hasClass(
element, “selected”)){
YAHOO.util.Dom.removeClass(
element, “selected”);
return false;
} else {
YAHOO.util.Dom.addClass(
element, “selected”);
return true;
}
}
Good pattern:
function toggle(element) {
var Dom = YAHOO.util.Dom;
if (Dom.hasClass(element, “selected”)){
Dom.removeClass(element, “selected”);
return false;
} else {
Dom.addClass(element, “selected”);
return true;
}
}
How we detect
This code insight counts the number of cases when an object member (e.g. Acme.util.Dom.hasClass) goes through more than two nesting levels (i.e. it has at least three dots to access the object member). Depending on the number of cases identified in the code, Highlight counts penalty points to the scanned file.
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.