Question

In: Computer Science

C# programming When a loop might execute many times, it becomes increasingly important to consider the...

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?

Solutions

Expert Solution

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,

  • & ( single ampersand ) – Logical AND operator
  • | ( single pipeline) – Logical OR operator

    Both of these operators are non short-circuit in nature.
  • && ( double ampersand ) – Conditional AND operator
  • || ( double pipeline) – Conditional OR operator

    Both of these are short-circuited operators and collectively knows as Conditional Logical Operators.

Order of Evaluation

Order of execution of any of these operators are from left to right. In the following lines of code,

  1. if(Expression1() && Expression2() && ....)   
  2. { }  

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.


Related Solutions

Determine how many times the innermost loop will be iterated when the algorithm segment is implemented...
Determine how many times the innermost loop will be iterated when the algorithm segment is implemented and run. (Assume that m and n are positive integers.) for j := 1 to m     for k := 1 to n         [Statements in body of inner loop.         None contain branching statements that         lead outside the loop.]     next k next j
Job role definition becomes increasingly important as projects grow in size and complexity. One of the...
Job role definition becomes increasingly important as projects grow in size and complexity. One of the tools available to project managers is the RACI chart. Review the following RACI Chart and address the questions: Are there clear delegations of authority? Are there multiple decision points within a single task/process? Would the team have questions about who does what? Is the Accountability level unclear? Task PM Engineer Construction Mgr Consultant Project Sponsor Engineering A A I R C Permits A C...
in c++ >>When is beneficial to use entry condition loop (for loop) and when is it...
in c++ >>When is beneficial to use entry condition loop (for loop) and when is it beneficial to use exit condition loop (while loop). Give an example for each loops.
All in C++ programming language 1. a.) convert for loop to while loop example b.) convert...
All in C++ programming language 1. a.) convert for loop to while loop example b.) convert while loop to for loop example 2.) pass one dimension array(and its size) to function example
12. As the world’s economy becomes increasingly interdependent, various exchange rates between currencies have become important...
12. As the world’s economy becomes increasingly interdependent, various exchange rates between currencies have become important in making business decisions. For many U.S. businesses, the Japanese exchange rate (in yen per U.S. dollar) is an important decision variable. This exchange rate (EXRJ) is shown in the following table by month for a two-year period: (c1p12) Period EXRJ Period EXRJ Year 1 Year 2     M1 127.36     M1 144.98     M2 127.74     M2 145.69     M3 130.55     M3 153.31     M4 132.04     M4 158.46     M5...
C programming. Explain by taking a programming example how do while loop is different from while...
C programming. Explain by taking a programming example how do while loop is different from while loop?
How many times will the following crontab entry execute during January 2018? 0 0 * 1...
How many times will the following crontab entry execute during January 2018? 0 0 * 1 1 rm -r /root/backup/* How many times will the following crontab entry execute during January 2018? 0 0 * 1 6 rm -r /root/backup/* List all of the dates the following crontab entry will execute during 2018 (this answer is a little tricky). 0 0 1/10 * 7 rm -r /root/backup/*
How many times will an "X" appear in the following nested loop? for (outer = 0;...
How many times will an "X" appear in the following nested loop? for (outer = 0; outer <=5; outer++) {for (inner = 1; inner <=4; inner+1) {cout<<("X");} } 9 10 20 24 none of the above
6 C++ Questions 13. True/False: every while loop is guaranteed to execute at least one time....
6 C++ Questions 13. True/False: every while loop is guaranteed to execute at least one time. 14. Assume there is a file named "cards.txt" in the current directory which contains 3 ints. Write a code snippet which reads in the three ints and outputs their average (mean) to the screen. 15. True/False: the following function prototype takes an array and its size as its parameters. If you change the value of the array's elements within the function, the changes persist...
Often times when a company becomes large enough, it will sell off a minority portion of...
Often times when a company becomes large enough, it will sell off a minority portion of their ownership to the public as shares to gain capital. This capital is then reinvested into the company to assist in new projects or expansion in general. For this week's discussion assignment, research how a company's stock is initially appraised when they decide to go public, how it is determined the number of shares are to be distributed and the advantages/disadvantages of common and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT