Is it bad to execute if (false) many times?

If I have a piece of code like this ...

if(!hasRunMethod) {
    runMethod();
    hasRunMethod = true;
}

... and this code is executed in a loop again and again, many times per second, although the code inside is called only once, is this bad coding practice? If so, what should I do instead?

+4
source share
1 answer

Quick testing (according to java version 1.8.0_05):

long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
    if(alwaysTrue) {

    }
}
long end = System.nanoTime();

end - start~ 1820,000 nanoseconds on average. this:

long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
    // if(alwaysTrue) {
    //   
    // }
}
long end = System.nanoTime();

end - start an average of ~ 1,556,000 nanoseconds.

as an added bonus:

long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
    if(true) {

    }
}
long end = System.nanoTime();

end - start ~ 1,542,000 nano seconds on average, same as comment.

Conclusion

if(someBool){} . , , , .

+3

All Articles