加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – .Net中字符串(或任何其他对象)的内存使用情况

发布时间:2020-12-15 08:37:10 所属栏目:百科 来源:网络整理
导读:我写了这个小测试程序: using System;namespace GCMemTest{ class Program { static void Main(string[] args) { System.GC.Collect(); System.Diagnostics.Process pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess(); long startBytes =
我写了这个小测试程序:
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();
        }
    }
}

Release版本中的输出是:

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

我假设GC.collect调用将删除已分配的字符串,因为它们超出范围,但它似乎没有.我不明白也无法找到解释.也许这里有人?

谢谢,
亚历克斯

解决方法

您正在查看专用内存大小 – 托管堆将扩展为容纳字符串,但是当字符串被垃圾回收时,它不会将内存释放回操作系统.相反,托管堆将更大,但拥有大量可用空间 – 因此,如果您创建更多对象,则不需要堆扩展.

如果要查看托管堆中使用的内存,请查看GC.GetTotalMemory.请注意,由于垃圾收集的复杂性,所有这些内容都存在一定程度的羊毛.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读