Here has a scientific article that deals only with this comparison. Moreover, the performance clearly depends on the applying in particular and the compiler of the language used.
In C#
, FOR
is a little faster. FOR teve uma média de 2,95-3,02 ms
. The While média de cerca de 3,05-3,37 ms
. Run the code yourself and see:
class Program
{
static void Main(string[] args)
{
int max = 1000000000;
Stopwatch stopWatch = new Stopwatch();
if (args.Length == 1 && args[0].ToString() == "While")
{
Console.WriteLine("While Loop: ");
stopWatch.Start();
WhileLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
}
else
{
Console.WriteLine("For Loop: ");
stopWatch.Start();
ForLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
}
}
private static void WhileLoop(int max)
{
int i = 0;
while (i <= max)
{
//Console.WriteLine(i);
i++;
};
}
private static void ForLoop(int max)
{
for (int i = 0; i <= max; i++)
{
//Console.WriteLine(i);
}
}
private static void DisplayElapsedTime(TimeSpan ts)
{
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
}
}
The noose for
is usually used when you know the number of iterations beforehand. For example to scroll through an array of 10 elements that you can use to loop and increment the counter 0-9
(or 1 a 10
).
On the other hand while
is used when you have an idea about the range of values in which to make an iteration, but do not know the exact number of iterations that occur.
for example:
while (!algumaCondicao()){
// Remove elemento (s)
// Adiciona elemento (s)
}
Here we don’t know exactly how many times the loop will run.
In addition, the FOR
is more of a convenience than a language constructor. For example, a FOR
be easily expanded into a while loop.
for ( c=0; c<10; c++ )
is equivalent to:
c=0;
while ( c<10 ) {
// alguns códigos loucos aqui
c++;
}
In addition, O FOR
is not limited to simple numerical operations, you can do more complex things like this (C syntax):
// uma lista encadeada simples
struct node {
struct node *next;
};
struct node; // declarando nosso nó
//iterar sobre todos os nós a partir do nó 'start' (não declarado neste exemplo)
for ( node=start; node; node=node->next ) {}
The result is an iteration over a simple chained list.
You can also have multiple initializers, conditions and instructions (depending on the language) as such: for(c = 0, d = 5; c <10, d <20; c ++, d ++).
It is a pity that the answer accepted is not really authored by the author and not only does not cite the source, it does not have the date that was made. The information may be out of date. In my tests, that’s not what happened. I think I’ll answer at least to complement this.
– Maniero