There was a task to know which code is faster and why:
//A
Stopwatch sw = new Stopwatch();
Int32[] a = new Int32[10000000];
int len = a.Length;
sw.Start();
//for (Int32 index = 0; index < len; index++)
//{
// a[index] = 6;
//}
//sw.Stop();
//B
for (Int32 index = 0; index < a.Length; index++)
{
a[index] = 6;
}
sw.Stop();
var time = sw.ElapsedMilliseconds;
The avarage time of approach B is little more than A. Does anybody explain why?
My guess would be because you are polling the length of the array each time you loop, whereas the A approach only has to check a cached value of the length. So, ultimately, this comes down to the idea of caching