【问题标题】:Simple way to keep track of how much memory a list is taking?跟踪列表占用多少内存的简单方法?
【发布时间】:2011-08-16 07:47:40
【问题描述】:
public class Players
{
    public int GUID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public Clans Clan { get; set; }

    public PlayerType Type { get; set; }
    public Groups Access { get; set; }
    public int Level { get; set; }
    public int RoomID { get; set; }

    public IPAddress IP { get; set; }
    public bool IsPlaying { get; set; }
    public bool IsProtected { get; set; }
    public bool IsBanned { get; set; }
    public bool IsInvisible { get; set; }

    public bool IsOnline()
    {
        return (IPAddress.Parse("0.0.0.0").Equals(this.ExtIP)) ? false : true;
    }

    public string GetIP()
    {
        return this.ExtIP.ToString();
    }
}

我有一个使用上述类的列表,我想知道如何跟踪该列表为每个添加的新用户或对已在其上的任何用户所做的每次更改或如何计算该列表占用了多少内存它(如果可能的话,用简单的方式解释从来都不是一个好的数学呵呵)?

如果有一个简单的代码可以告诉我,一旦列表更新或有新条目进入/退出,我也会很感激。

这个应用程序在 linux 上运行,使用 MySQL 作为数据库,我非常依赖数据库,因为我在 VPS 上运行它,所以消耗了大量的 cpu/内存。

为了优化它,我正在考虑在启动时加载一些数据并每 X 分钟管理一次更新,并且只更新即时重要的数据,而不是查询数据库以获取我需要使用的大部分信息。

首先,我想进一步了解如何监控内存使用情况以及我拥有或可以用于此目的的列表类型。

【问题讨论】:

    标签: c# list .net-4.0 memory-management


    【解决方案1】:

    您可以使用GC.GetTotalMemory() Method 记录快照时间点内存使用情况:

    // Measure starting point memory use
    GCMemStart = System.GC.GetTotalMemory(true);
    
    // Perform allocations
    
    GCMemEnd = System.GC.GetTotalMemory(true);
    

    [如果forceFullCollection参数为真,该方法等待一个 系统收集垃圾和返回前的短暂间隔 完成对象]

    【讨论】:

    • 很好,不知道 gc 的这个函数,你所说的“快照时间点”是什么意思,比如在之前和之后使用它?
    • 有点离题,但除此之外,还有推荐的列表大小限制吗?
    • 大奖:没有更多细节很难回答,但与所有内存使用一样,尽量减少它,但不牺牲代码清晰度;)
    猜你喜欢
    • 2011-01-03
    • 2010-10-25
    • 2018-09-17
    • 2011-05-16
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2010-09-13
    相关资源
    最近更新 更多