简体   繁体   中英

Optimizing conditional code inside nested for-loops

Let's say I have some code that looks something like below.

boolean changecode = 0;

for (int i=0; i<4; i++) {
    //some code
    for (int j=0; j<4; j++) {
        //some more code
        if (changecode) {
            //Code A
        } else {
            //Code B
        }
    }
}

This code would run the if-condition every time the loops were run, ending up executing it 16 times, which isn't really optimized. Now, I could of course do this:

boolean changecode = 0;

if (changecode) { 
    for (int i=0; i<4; i++) {
        //some code
        for (int j=0; j<4; j++) {
            //some more code
            //Code A
        }
    }
} else {
    for (int i=0; i<4; i++) {
        //some code
        for (int j=0; j<4; j++) {
            //some more code
            //Code B
        }
    }
}

But i suppose this isn't really optimized either, thinking about all the repetition of code. Is there a way to make the conditional run in the outer layer and replace what code should be ran in the middle of the nested for-loop?

I think the compiler will be able to optimize this away, but for the question's sake, you could do

Runnable code = changecode 
                   ? () -> codeA() 
                   : () -> codeB();
for (int i=0; i<4; i++) {
    //some code
    for (int j=0; j<4; j++) {
        //some more code
        code.run();
    }
}

In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.

As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.

In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.

It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM