In C++, is it faster to store the limit of a loop in a variable than evaluating the value?
For example:
Is it a slower approach to use
for(int i=0; i<n*n+2*n; ++i)
{ .... }
than doing the following?
for(int i=0, limit=n*n+2*n; i<limit; ++i)
{ .... }
For clarity, assume that n
is some given variable that remains unchanged during the course of the loop.
In the java for loop, there is no limit. You might be thinking of BASIC. In the java for loop, the 2nd expression is the termination expression. The loop will keep looping for as long as the termination expression is true .
A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".
The while loop checks the condition first, and if it returns true, the code within it runs. The loop continues until the condition provided returns false, then stops. Alternatively, the do while loop runs its code once before checking the condition and runs again only if the condition is true.
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.
If n
is a globally declared non-volatile
variable, then the behaviour of
for (int i = 0; i < n * n + 2 * n; ++i)
is unspecified. A compiler is allowed to optimise n * n + 2 * n
to be evaluated once even if another thread modifies n
. Furthermore, if another thread is able to modify n
, then you should take steps to avoid the potential for simultaneous read and writes of n
(the behaviour of which is undefined). Consider using std::atomic<int>
as the type for n
.
So really it's appropriate to introduce limit
anyway if you want the stopping condition to be dependent on the value of n
observable when program control reaches the for
loop, irrespective of any performance considerations. Consider therefore
for (int i = 0, limit = n * n + 2 * n; i < limit; ++i)
which has the advantage that the scope of limit
doesn't leak into the surrounding statements.
But if you are able to, you could always run the loop backwards:
for (int i = n * n + 2 * n - 1; i >= 0; --i)
Be very careful though with unsigned
types if you adopt that idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With