4

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

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

...and that code is being executed in a loop over and over, many times every second, even though the code inside is only called once, is this bad coding practice? If so, what should I do instead?

  • 4
    if you can put it outside your loop, that is always better. however, both the compiler and the processor will be able to optimize this quite well. see http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array?rq=1 on predictive branching – njzk2 Aug 06 '14 at 16:59
  • Since there's branching the performance hit is smaller than you expect. Though with your current code snippet it's not enough to give you useful information, as it really depends on what you're trying to do. Perhaps you might want to use `return true;` instead of assigning the booleam. – Unihedron Aug 06 '14 at 17:01
  • @njzk2 Thanks, I'm always a little bit paranoid with optimization, so it's great to hear that won't be as bad as I though it would – Nicholas Hollander Aug 06 '14 at 17:01
  • 1
    @NicholasHollander Being paranoid about optimization is fine, but it's very common to be too paranoid, too early. Is this actually slowing down your code? Can something else modify `hasRunMethod`, like another thread, so the JIT can't optimize this away after a few iterations? – Dave Newton Aug 06 '14 at 17:04
  • There is very little overhead in that code segment. A good JITC can probably get the cost to zero in many cases. – Hot Licks Aug 06 '14 at 17:10

1 Answers1

3

Quickly tested (on 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 averages ~1,820,000 nano seconds. 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 averages ~1,556,000 nano seconds.

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 averages ~1,542,000 nano seconds, same as commented out.

Conclusion

if(someBool){} inside a loop has some performance impact. But it's so negligible I find it hard to think of a bottleneck sensitive enough for it to matter.

Assaf
  • 1,352
  • 10
  • 19