C/C++: is GOTO faster than WHILE and FOR?

Artur Iwan picture Artur Iwan · Mar 20, 2011 · Viewed 10.4k times · Source

I know, that everybody hates GOTO and nobody recommends it. But that's not the point. I just want to know, which code is the fastest:

  1. the goto loop

    int i=3;
    loop:
    printf("something");
    if(--i) goto loop;
    
  2. the while loop

    int i=3;
    while(i--) {
        printf("something");
    }
    
  3. the for loop

    for(int i=3; i; i--) {
        printf("something");
    }
    

Answer

Gabe picture Gabe · Mar 20, 2011

Generally speaking, for and while loops get compiled to the same thing as goto, so it usually won't make a difference. If you have your doubts, you can feel free to try all three and see which takes longer. Odds are you'll be unable to measure a difference, even if you loop a billion times.

If you look at this answer, you'll see that the compiler can generate exactly the same code for for, while, and goto (only in this case there was no condition).