Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking condition inside a loop

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);
            }
        }
    }
like image 839
Vishal Avatar asked Apr 20 '26 19:04

Vishal


1 Answers

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...

like image 122
DigitalRoss Avatar answered Apr 23 '26 08:04

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!