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, it told me that the code allocates roughly 40 MB. Around 20 MB is allocated to String
, 9 MB to Char[]
, 5 MB to StringBuilder
and 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 one allocates around 5 MB. 4 MB is allocated to Char[]
.
The only thing I get is that array a
should require 1 MB (250,000 * 4).
Why is there such a massive difference ? Why are all those objects required for the first code and how do I reduce the memory allocation ?
Most likely the memory increase is because of the complexity involved in parsing the format string.
In your first case, it has to parse the format string, get a localized string representing the integer and put it in the right place of the format string.
In your second case you are outputting just a single value, and even more so, a plain string. It is very trivial in comparison.
If you are interested in what goes on under the covers you can use .NET Reflector and have a look at the WriteLine
overloads.
It's kind of runtime-specific question.
My guess would be that first code uses so much memory because of conversion of int
to String
, which has to be made in order to format string for Console.WriteLine
correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With