I attempt to allocate a large chunk of memory as a byte array (400MB)
public static void Main(string[] args)
{
const int MegaByte = 1048576;
byte[] bytes = new byte[400 * MegaByte];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = 3;
}
Console.WriteLine("Total array length : {0}", bytes.Length);
Console.WriteLine("First byte = '{0}' Last byte = '{1}'", bytes[0], bytes[bytes.Length - 1]);
Console.Read();
}
Output:
Total array length : 419430400
First byte = '3' Last byte = '3'
As expected I see a large jump in Windows Task Manager for the memory that is being used, when I just allocated 400MB of memory. However if I replace the forloop usage to just using first and last bytes:
public static void Main(string[] args)
{
const int MegaByte = 1048576;
byte[] bytes = new byte[400 * MegaByte];
bytes[0] = 0;
bytes[bytes.Length - 1] = 2;
Console.WriteLine("Total array length : {0}", bytes.Length);
Console.WriteLine("First byte = '{0}' Last byte = '{1}'", bytes[0], bytes[bytes.Length - 1]);
Console.Read();
}
Output:
Total array length : 419430400
First byte = '0' Last byte = '2'
No large jump in used memory is observed even though the length of the allocated array is said to be the same. I had an assumption that if we build in Debug there won't be such optimizations. Are there some optimizations that are done during 'Debug' builds or do such things get optimized at a lower level when IL gets compiled?