Le_Square
Le_Square

Reputation: 7

any differences between "while(true) { code }" and "for(int i = 0; i < n; i++) { code }"

supposed I have this code

while (true) {
  // do things
  if (condition) break;
}

if I can always determine that the while loop stops after less than n times during runtime, should I write this instead

for (int i = 0; i < n; i++) {
  // do things
  if (condition) break;
}

this is clearly micro optimization and i should not worry about it too much. nevertheless I want to know the answer out of curiosity that if the compiler can use the extra information for some obscure optimizations.

Upvotes: -3

Views: 157

Answers (2)

Mike Vine
Mike Vine

Reputation: 9852

In your scenario - when you know the loop will break early - then there's no functional difference.

For performance, however, you probably should use the while(true). The reason being that the branch at the end of the while(true) loop will be an unconditional branch back to the beginning. This means that any processor branch-predictor will not need to guess whether the branch is taken or not. In the for case the branch at the end is a predicated branch that is always taken. This means the branch predictor cannot be of any use and may get it wrong.

Also, the code doesn't need to maintain and update a count with the while loop which is a tiny win.

That said, this is the smallest of microoptimsations and unless this is on a really hot path what ever reads best and/or leads to less maintenance is the right solution. Even if you do choose to go down this route you'd probably want to run performance analysis on it to be sure.

Upvotes: 1

you should use "while true" because of saving memory.

Upvotes: -6

Related Questions