High memory usage with Console.WriteLine()

 ̄綄美尐妖づ 提交于 2019-12-23 07:58:15

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6430380/high-memory-usage-with-console-writeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!