Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is while faster than for?

As in the topic, I learnt in school, that loop for is faster than loop while, but someone told me that while is faster.

I must optimize the program and I want to write while instead for, but I have a concern that it will be slower?

for example I can change for loop:

for (int i=0; i<x; i++)
{
   cout<<"dcfvgbh"<<endl;
}

into while loop:

i=0;
while (i<x)
{
    cout<<"dcfvgbh"<<endl;
    i++;
}
like image 693
Zosia Avatar asked Jan 02 '14 22:01

Zosia


2 Answers

The standard requires (§6.5.3/1) that:

The for statement
for ( for-init-statement conditionopt; expressionopt) statement
is equivalent to

{
    for-init-statement
    while ( condition ) {
        statement
        expression;
    }
}

As such, you're unlikely to see much difference between them (even if execution time isn't necessarily part of the equivalence specified in the standard). There are a few exceptions listed to the equivalence as well (scopes of names, execution of the expression before evaluating the condition if you execute a continue). The latter could, at least theoretically, affect speed a little bit under some conditions, but probably not enough to notice or care about as a rule, and definitely not unless you actually used a continue inside the loop.

like image 109
Jerry Coffin Avatar answered Oct 29 '22 08:10

Jerry Coffin


For all intents and purposes for is just a fancy way of writing while, so there is no performance advantage either way. The main reason to use one over the other is how the intent is translated so the reader understands better what the loop is actually doing.

like image 33
Gabe Avatar answered Oct 29 '22 08:10

Gabe