Optimizing conditional code inside nested for-loops

h7x4 :

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?

Veselin Davidov :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128709&siteId=1