views:

123

answers:

4

Hi,

If "flag" is true I have to perform step no. 1 otherwise skip it. Is there a way out to skip this unnecessary repetitive check within the loop. (As the value of flag is not changing while the execution of the loop)

private void method(boolean flag) {
     while (man > woman) {
      if (flag) {
       // Step no. 1
       System.out.println(flag);
      }
     }
    }
A: 

It depends on the scope of do. If do is always true, you don't need to check for it and you can remove if (do). There is no reason to set a variable to true if it will always be true. What is the scope?

Brandon G
A: 

If the value of do changes at any time in the loop, you have to check for it every time unless you rewrite the code so that the do == true state is handled outside the current loop (perhaps in a smaller loop; it depends on what you're trying to do [no pun intended]).

Michael Todd
+8  A: 

I'm not sure it is productive to worry about optimizations at this level. Generally it is more important to get the program working and move on to the next problem.

Having said that, there is an optimization called loop unswitching that some compilers will do for you. They duplicate the loop, once with and once without the conditional, and move the conditional outward to select the loop. (In your example you could make the entire loop conditional but I presume that's just an artifact of simplification for Stack Overflow.)

But this is just one more reason not to worry too much about optimizations, at least, not until you have a profile and you know that this region of code is responsible for detectable amounts of runtime.

Still, it's best to write code as cleanly as you can and puzzling through issues like this will teach you good things...

In fact, loop-invariant conditionals bother me too. I don't believe there is a general answer. There are fancy answers involving higher order functions or lambdas, "leave-it-to-the-compiler" answers, refactor-the-whole-outer-routine answers ... I would generally approve of whatever makes the code appear smaller. You have to prioritize in order to discriminate...

DigitalRoss
A: 
while (man > woman) {

Beware of infinite loops here :-)

Vincent Robert