Why you should care
Reducing the dotation usage can win 50% of the time consumed by this function.
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.
JavaScript namespacing, such as the technique used in YUI, is a source of frequently accessed nested properties.
How we detect
Note: the scope for tracking derefereces reuses is limited to the content of a function, excluding inner functions contents.
Bad Code
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 Code
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; } }
References
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.