字符串(或其它任何物体)在.net中的内存使用情况 [英] Memory usage of strings (or any other objects) in .Net

查看:95
本文介绍了字符串(或其它任何物体)在.net中的内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个小测试程序:

I wrote this little test program:

using System;

namespace GCMemTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.GC.Collect();

            System.Diagnostics.Process pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();

            long startBytes = pmCurrentProcess.PrivateMemorySize64;

            double kbStart = (double)(startBytes) / 1024.0;
            System.Console.WriteLine("Currently using " + kbStart + "KB.");

            {
                int size = 2000000;
                string[] strings = new string[size];
                for(int i = 0; i < size; i++)
                {
                    strings[i] = "blabla" + i;
                }
            }

            System.GC.Collect();

            pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
            long endBytes = pmCurrentProcess.PrivateMemorySize64;

            double kbEnd = (double)(endBytes) / 1024.0;
            System.Console.WriteLine("Currently using " + kbEnd + "KB.");

            System.Console.WriteLine("Leaked " + (kbEnd - kbStart) + "KB.");
            System.Console.ReadKey();
        }
    }
}

在发布版本的输出是:

Currently using 18800KB.
Currently using 118664KB.
Leaked 99864KB.

我假设GC.Collect的通话将删除分配的字符串,因为他们走出去的范围,但它似乎没有。我不明白,我也不能为它找到一个解释。也许有人在这里?

I assume that the GC.collect call will remove the allocated strings since they go out of scope, but it appears it does not. I do not understand nor can I find an explanation for it. Maybe anyone here?

谢谢, 亚历克斯

推荐答案

您正在寻找在专用内存大小 - 托管堆中将扩大,以适应字符串,但它不会释放内存回操作当字符串被垃圾回收系统。相反,托管堆会比较大,但是有很多的自由空间 - 因此,如果您创造更多的对象,也不会要求堆展开

You're looking at the private memory size - the managed heap will have expanded to accommodate the strings, but it won't release the memory back to the operating system when the strings are garbage collected. Instead, the managed heap will be bigger, but have lots of free space - so if you create more objects, it won't require the heap to expand.

如果你想看看内存的使用的托管堆内,看<一href="http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory%28v=VS.100%29.aspx"><$c$c>GC.GetTotalMemory.注意,由于所述垃圾收集的复杂性,有内的所有的这一定量的像羊毛的

If you want to look at the memory used within the managed heap, look at GC.GetTotalMemory. Note that due to the complexities of garbage collection, there's a certain amount of woolliness within all of this.

这篇关于字符串(或其它任何物体)在.net中的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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