Is the Break keyword the most efficent way to exit a for loop? C/C++

Viewed 236

Is break the most efficient way to exit a loop? In the code snippet below, would line A or line B be the more efficient way to exit the loop? Any links to material on how the break instruction works under the hood would be appreciated.

for (int i = 0; i < 10; i++) {
       cout << i << endl;
       if (i == 3) {
           break;  // A
           i = 15; // B
       }
   }

I assume the difference is trivial in most situations, and that A is faster because B requires an assignment, an increment, and then a comparison, but I don't actually know how break works and it's better to know than assume. Thanks!

4 Answers

Let's compile the following code and look at the assembly:

#include <stdio.h>

int loop_with_break() {
    for (int i = 0; i < 10; i ++) {
        puts("Hello, world!");
        if (i == 3) {
            break;
        }
    }
}

int loop_with_assignment() {
    for (int i = 0; i < 10; i ++) {
        puts("Hello, world!");
        if (i == 3) {
            i = 10;
        }
    }
}

int main() {
    loop_with_break();
    loop_with_assignment();
}

assembly of loop with break assembly of loop with assignment As you can see, when you use break, if i == 3, it'll jump straight out of the loop to the end of the function, whereas if you use i = 10, it'll set i to 10, increment it by 1, then do the comparison, which is slower. However, this was compiled with no optimizations. If you use optimizations, they both end up becoming the same thing. However, since break is more readable and these optimizations are not guaranteed, you should use it for breaking out of loops.

The keyword break will just quit the loop without any comparison made in the loop condition. If you use i = 15 syntax, the loop will iterate next time to verify whether the variable i is greater than 10, if so, then quit.

In short words, break will break the loop without thinking anything, whereas i = 15 will lead one more iteration to look if the condition satisfies it.

You're right! Actually break keyword is very faster for breaking loop!

In your example, if you use line A, then as soon as control reaches this statement, it will immediately break the loop.

On the other hand, if you use line B, then first the assignment will be performed and again the control will go to the condition checking and when the condition will get false then it will exit from the loop!

if you choose while loop you can prefer to make condition false in the while loop. But in this case using break make sense.

Related