I've been reading tips about Javascript performance boosting and one tip said to cache all the variables (that don't change) in the loops comparer statement and I was wondering if this also applied to .NET.
Assuming I had a simple for loop, which one of the following would be faster or would they be the same?
No Cache:
for (int i = 0; i < someArray.Length; i++)
{
}
With Cache:
for (int i = 0, count = someArray.Length; i < count; i++)
{
}
According to the article "caching" the value of Length
cuts out one operation in the loop because its faster to access local variables compared to accessing members of an object.
Is it actually faster declaring a local variable compared to simply accessing the member? Does the compiler pick up on this and automatically cache the value? Is there any negatives in declaring a local variable over accessing the member?
Whilst speed is probably a key factor here, its not the only one. My next question would probably be which one is more efficient. Which uses less memory allocations? Which performs less stack manipulation? etc...
From comments, it seems accessing array lengths is pretty fast. Lets say I use an IList<>
instead. Would caching the value of Count
be faster than retrieving it each iteration?