Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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 ?

like image 473
rohit89 Avatar asked Jun 21 '11 18:06

rohit89


2 Answers

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.

like image 167
Skurmedel Avatar answered Nov 12 '22 23:11

Skurmedel


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.

like image 42
Dr McKay Avatar answered Nov 12 '22 23:11

Dr McKay