I have a loop like
for (int i = 2; i <= ViewBag.numPages; ++i)
and I'm wondering if it'll be faster if I write it as
for (int i = 2, n = ViewBag.numPages; i <= n; ++i)
Please give me a deep (low-level) explanation if possible
I have a loop like
for (int i = 2; i <= ViewBag.numPages; ++i)
and I'm wondering if it'll be faster if I write it as
for (int i = 2, n = ViewBag.numPages; i <= n; ++i)
Please give me a deep (low-level) explanation if possible
Does the dot operator cost anything in terms of operations?
It depends. For your ASP.NET code:
for (int i = 2; i <= ViewBag.numPages; ++i)
...then the above may be subject to optimisations (or perhaps CPU caching) so anything you do in an attempt to optimise may not be noticeable.
However, your question title does not mention ASP.NET (though it is later tagged asp.net ) so imagine if ViewBag
was actually a COM object.
for (int i = 2; i <= ViewBag.numPages; ++i)
...then that would be very expensive and not subject to .NET optimisation I would not think. Invoking COM, particularly via IDispatch
is significantly slower than accessing a .NET property on a local object.
So in the case of COM you should:
for (int i = 2, n = ViewBag.numPages; i <= n; ++i)
Assuming that ViewBag.numPages
stays constant for the duration of your loop, I would favor the second variant, i.e.:
for (int i = 2, n = ViewBag.numPages; i <= n; ++i)
Why?
Perhaps your first numPages
is a simple field, but if it is a non-trivial property, your loop has to evaluate it (call its getter) before each iteration, which is certainly costlier than evaluating it once and then caching the result.
Compiler optimizations are an implementation detail of the compiler, you do not know what exactly the compiler does for you to improve performance.
Caching ViewBag.numPages
manually means that you won't have to rely on an optimization that the compiler may or may not do for you.
That being said, if ViewBag.numPages
is a (constant) field, not a property, then both code variants are likely so close in execution speed (in the best case, we're talking about the difference between accessing a CPU register vs. accessing atomically one memory location that might be in the CPU memory cache) that the difference doesn't matter at all.