in some perf critical program (single threaded), if I have arrays of primitive types, and need to access the same index of those more than once in loops.
Should I us
Lets test this:
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7};
int t = arr[3];
int a = 0;
var start = DateTime.UtcNow;
for (int i = 0; i < 1000000000; i++)
{
a += t;
}
Console.WriteLine(a);
Console.WriteLine(DateTime.UtcNow-start);
a = 0;
start = DateTime.UtcNow;
for (int i = 0; i < 1000000000; i++)
{
a += arr[3];
}
Console.WriteLine(a);
Console.WriteLine(DateTime.UtcNow - start);
Output:
-294967296
00:00:02.1925000
-294967296
00:00:03.4250000
Yes its slower to access the array repeatedly.