Sunday, May 20, 2007

Short Circuit Evaluation

What is Short Circuit? In the simplest terms, Short Circuit is a control structure put in place to allow the control of the program to be passed onto a different set of instructions while minimizing the evaluation of the code. It operates on booleans or boolean expressions in which the second boolean or boolean expression is only evaluated if the first one does not suffice to determine the value of the entire expression.

Consider the following example:

bool hasMoney = false;
double totalMoney = 0;
if (hasMoney && totalMoney > 5)
{
MessageBox.Show("Buy burger.");
}

If we have no money (hasMoney=false) then there is no need to check and see if the amount of money we have is greater than 5 bucks so the boolean expression on the right hand side of boolean operator "&&" will not be evaluated in this case.

You can really appreciate short circuiting in the following example:

bool hasMoney = false;
double totalMoney = 0;
if (hasMoney && checkTotalMoney())
{
MessageBox.Show("Buy burger.");
}


As you can see, this is just a simple example to demonstrate how short circuit evaluation works but what if in the method checkTotalMoney() you have some lengthy code that goes on to evaluate if you have enough money to pay for the burger and the taxes as well?

Things just get a little bit more complicated and you can see all of that work is skipped if the boolean expression on the left of the operation becomes false. This is important to consider because if you have checkTotalMoney() on the left, the method will be evaluated to determine its value before it can move on to the second expression on the right hand side.

Knowing how short circuit evaluation works and carefully design expressions that use conditional logical operators you can greatly improve your code and boost the performance of your applications by avoiding unnecessary work. You can read more about short-circuit evaluation here.

No comments: