High memory usage with Console.WriteLine ()

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?

+7
source share
2 answers

Most likely, the increase in memory is due to the difficulty in analyzing the format string.

In your first case, it should parse the format string, get a localized string representing an integer, and put it in the right place on the format string.

In your second case, you output only one value, and even more so, a regular string. This is very trivial in comparison.

If you're interested in what's happening under the covers, you can use the .NET Reflector and see WriteLine overloads.

+8
source

This is a kind of runtime-dependent question.
My guess would be that the first code uses so much memory due to the conversion of int to String , which must be done to properly format the string for Console.WriteLine .

+3
source

All Articles