Can someone please help me understand why is accessing arrays using a linear increment for index approximately 3-4 times faster than using random index?
Is there any way of making the random index access times faster?
Please consider the following test code, it return ~3 seconds for linear, ~9-10s for random:
public static void test()
{
var arr = new byte[64 * 1024 * 1024];
byte b = 0;
var sw = new Stopwatch();
double timeSum = 0;
for (var i = 0; i < arr.Length; i++)
{
sw.Restart();
b = arr[i];
sw.Stop();
timeSum += sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Linear access : " + timeSum + " ms");
timeSum = 0;
var rng = new Random();
var rnum = 0;
for (var i = 0; i < arr.Length; i++)
{
rnum = rng.Next(0, arr.Length - 1);
sw.Restart();
b = arr[rnum];
sw.Stop();
timeSum += sw.Elapsed.TotalMilliseconds;
}
sw.Stop();
Console.WriteLine("Random access : " + timeSum + " ms");
}