public static void Main() { int size = 250000; var a = new int[size]; for (int i = 0; i < size; i++) Console.WriteLine("{0}", a[i]); }
When I tested the above code with CLRProfiler, he told me that the code allocates approximately 40 MB. About 20 MB is allocated String , from 9 MB to Char[] , from 5 MB to StringBuilder and from 3 MB to Int32 .
public static void Main() { int size = 250000; var a = new int[size]; for (int i = 0; i < size; i++) Console.WriteLine("0"); }
This allocates about 5 MB. 4 MB is allocated Char[] .
The only thing I get is that array a should require 1 MB (250,000 * 4).
Why is there such a huge difference? Why are all these objects necessary for the first code and how to reduce memory allocation?
rohit89
source share