Optimization Monday — Part VI: expression order
Optimization Monday December 3rd, 2007JavaScript has the nice ability to stop evaluating expressions in a condition as soon as the condition result is final.
function test(){ alert("this message will never be shown!"); return true; } if( true || test() ){ // .. } if( false && test() ){ // .. }
Since expressions are evaluated from left to right we have the following possibilities to optimize the expression order:
- align less complex expressions left
- for disjunctions: put the expression which will most likely be true to the left
- for conjunctions: put the expression which will most likely be false to the left
- group depending expressions
Of course the rules also apply to nested expressions.
This example
if( ( (complexCalculation() < 42) && ( (userAgentVersion < 7) && activexDisabled() && (getUserAgent() == "Internet Explorer") ) ) || ( (value > 0) ) ){ // .. }
can be optimized to
if( (value > 0) || ( ( (getUserAgent() == "Internet Explorer") && (userAgentVersion < 7) && activexDisabled() ) && (complexCalculation() < 42) ) ){ // .. }