If givin some situation that you can do a loop of a certain event or function that needed to be solved using loops, where you can achieve these by any kind of loop. How can we determine the difference between each loops that can be used based on their speed, efficiency, and memory usage? Like for example, you have these loops
for(int i=0;i<10;i++) {
array[i] = i+1;
}
int i = 0;
while(i<10) {
array[i] = i+1;
i++;
}
The above example have the same output, of course you cannot see the difference between them when executed since this is just a small process, what if you are processing an enormous loop that's eating up your memory? Which loop is better to use? Is there a proper measure when to use what loop?
Edit:
for pakore answer,
From your answer I can safely say that If I reorder my variables where most of the variables that are dependent are far from each other (with other lines inbetween) could have been more efficient. Say for example,
a=0;
b=1;
c=5;
d=1;
for(int i=0; i<10;i++)
{
a=b*CalculateAge()+d;
m=c+GetAvarage(a);
d++;
}
and
a=0;
b=1;
c=5;
d=1;
for(int i=0; i<10;i++)
{
a=b*CalculateAge()+d;
d++;
m=c+GetAvarage(a);
}
The later is more efficient than the first one since in the later I have called an outside method on the first line and the second line is independent from the result of the first line than on the third line.
Since the first example will wait for the result of the first line before executing the second line and on the third, and the second example has already executed the second line while waiting for the result of the first line.
Conclusion:
An optimized loop doesn't mater what kind of loop you are using. As what pakore explained, and polygenelubricants, the main thing that you can mind in your loop is how your code is written inside. It is the compilers job to optimize your code, it also helps if you optimize your code according to its dependency with each variable as what pakore explain below.