Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
    }
    
like image 881
Artur Iwan Avatar asked Mar 20 '11 05:03

Artur Iwan


1 Answers

Write short programs, then do this:

gcc -S -O2 p1.c 
gcc -S -O2 p2.c 
gcc -S -O2 p3.c 

Analyze the output and see if there's any difference. Be sure to introduce some level of unpredictability such that the compiler doesn't optimize the program away to nothing.

Compilers do a great job of optimizing these trivial concerns. I'd suggest not to worry about it, and instead focus on what makes you more productive as a programmer.

Speed and efficiency is a great thing to worry about it, but 99% of the time that involves using proper data structures and algorithms... not worrying about whether a for is faster than a while or a goto, etc.

like image 161
Matthew Avatar answered Oct 18 '22 03:10

Matthew