Home > Software design >  Is performance gained when using continue in a for-loop
Is performance gained when using continue in a for-loop

Time:08-14

continue first? or Should the code just go ahead?

Example:

for (int a : array) {
    if (map.containsKey(a))
        continue;
    ~~~
}

//or

for (int a : array) {
    if (!map.containsKey(a)) {
        ~~~
    }
}

Which phrase is faster? Or is there no difference in performance? Then what's the reason?

CodePudding user response:

They are entirely indistinguishable. Java, like many languages, compiles to bytecode, JVM bytecode in this case. And at the bytecode level, things like if statements don't exist. They get compiled down to conditional and unconditional jumps to labels. Your first code block will compile to a conditional jump back to the top of the loop. Something like

// Pseudocode
loop:
  _cond = map.containsKey(a)
  jump_if_true loop, _cond
  ...
end:
  jump loop

Your second will compile to something like

// Pseudocode
loop:
  _cond = map.containsKey(a)
  jump_if_false end, _cond
  ...
end:
  jump loop

And since end is an unconditional jump to loop, any good optimizer will turn this, immediately, into the former.

Just to be sure, I took the two functions you proposed above (replacing ~~~ with a System.out.println) and compiled them. They produce, verbatim, the same bytecode. After decompiling back to Java, they look entirely identical.

So don't micro-optimize. Write your code, and trust the compiler to handle things within its control. "Should I use continue or if here" is a micro-optimization. "Can I turn this triple nested loop into fewer iterations" is probably a good thing to ask up-front.

CodePudding user response:

I think this would depend on how much is being done inside the for loop. If its something small that can be executed very quickly, there wouldn't be a huge difference between the two.

  • Related