In: Computer Science
C# programming
When a loop might execute many times, it becomes increasingly important to consider the number of evaluations that take place. How can considering the order of evaluation of short-circuit operators affect the performance of a loop?
ORDER OF EVALUATION OF SHORT-CIRCUIT OPERATORS AFFECTING PERFORMANCE OF A LOOP
Short-circuit is a method for evaluating logical operators AND and OR. In this, the whole expression can be evaluated to true or false without evaluating all sub expressions.
Considering the following example
if (false && Condition1())
{
//inside code won't work in any case
}
in the above if clause, Condition1() will not be evaluated because whatever the value of Condition1() the whole expression will be false.If we use & instead of &&, it will execute Condition1() also. So always try to stick with short-circuited version.
&& Vs & or || Vs |
AND, OR operators can be found in the following ways,
Order of Evaluation
Order of execution of any of these operators are from left to right. In the following lines of code,
Expression1 will be evaluated first then Expression2 and so on.
How to Use && in C#
Prevent Exceptions
if (array.Count() >= 5 && array[4] % 2 == 1)
{
//print message here
}
If the && were replaced with &.it will cause Index was outside the bounds of the array exception when array does not contains 5 elements.
Ordering Expressions to Reduce Performance Impact
order of evaluation is from left to right.So if you have a series of operands for && operator as below and each of them are independent on other expressions:
if (Validations() && CheckUserExistance() && ..... && IsAuthorised())
{
//Some Operations
}
It is better to arrange them in the order of their complexity.
Side Effect
Consider the following example
int i = 0;
if (true && (++i < 60)) {
//code goes here
}
//value of i is 1
if (false && (++i < 60)) {
//inside code will not execute
}
// value of i remains as 1
As a result of short circuiting the second operand in the second if clause will not execute, so value of i remains same as before. This effect is called Side effect.
So when we use them, you should be aware of this effect and these effects are seen in rare situations.
Therefore, Short circuited logical operators in C# are && and ||, They are efficient and fast versions of logical operators in C#. So it is a good practice to use them.