高内存使用率为Console.WriteLine() [英] High memory usage with Console.WriteLine()

查看:312
本文介绍了高内存使用率为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]);
}

当我CLRProfiler测试上面的代码,它告诉我的代码中分配大约40 MB。大约20 MB分配给字符串,9 MB到的char [] ,5 MB到 StringBuilder的和3 MB到的Int32

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");
} 



这一次分配约500 MB。 4 MB被分配到的char []

我得到的唯一的事情就是数组 A 应该需要1 MB(250,000 * 4)。

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.

如果你有兴趣,你可以使用的。NET的反射并看看在的WriteLine 重载。

If you are interested in what goes on under the covers you can use .NET Reflector and have a look at the WriteLine overloads.

这篇关于高内存使用率为Console.WriteLine()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆