Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are while loops more efficient than for loops

Tags:

c++

I was told that a while loop was more efficient than a for loop. (c/c++) This seemed reasonable but I wanted to find a way to prove or disprove it.

I have tried three tests using analogous snippets of code. Each containing Nothing but a for or while loop with the same output:

  1. Compile time - roughly the same
  2. Run time - Same
  3. Compiled to intel assembly code and compared - Same number of lines and virtually the same code

Should I have tried anything else, or can anyone confirm one way or the other?

like image 465
mreff555 Avatar asked Jan 10 '16 21:01

mreff555


People also ask

Why are while loops better than for loops?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

Which loop is more efficient?

Among these 3 versions of loops which one is faster… their semantic is equivalent. if your compiler is smart enough, the cpu instructions generated are exactly the same. so none of them is faster than the other.

Which is easier while loop or for loop?

A while loop is a little easier to explain than a for loop because a while loop will simply run the same code over and over until the condition becomes false. Let's take a look at a simple example of a while loop!

Which loop is more efficient in C++?

Usually pre-increment / pre-decrement is faster than post-increment/post-decrement, because post-<> require to save a temporal value for returning.

Why is while better than for?

While loop is a loop statement used for the repeated execution of the statements. It is preferred when the loop statement is required and a number of iterations are not defined. In case the condition is not known, it shows an error unlike for loop which will have infinite iterations.


1 Answers

All loops follow the same template:

{
// Initialize
LOOP: 
    if(!(/* Condition */) ) {
        goto END
    }

    // Loop body

    // Loop increment/decrement
    goto LOOP
}
END:

Therefor the two loops are the same:

// A
for(int i=0; i<10; i++) {
    // Do stuff
}

// B
int i=0;
while(i < 10) {
    // Do stuff
    i++;
}

// Or even
int i=0;
while(true) {
    if(!(i < 10) ) {
        break;
    }

    // Do stuff
    i++;
}

Both are converted to something similar to:

{
int i=0;
LOOP: 
    if(!(i < 10) ) {
        goto END
    }

    // Do stuff

    i++;
    goto LOOP
}
END:

Unused/unreachable code will be removed from the final executable/library.

Do-while loops skip the first conditional check and are left as an exercise for the reader. :)

like image 190
Caramiriel Avatar answered Oct 03 '22 06:10

Caramiriel