【问题标题】:Is this an optimal chain in terms of memory management?这是内存管理方面的最佳链吗?
【发布时间】:2013-10-26 00:10:59
【问题描述】:

我们有一个将 C# poco 对象加载到内存中的系统。 (从磁盘上的数据源反序列化)。它们进一步缓存在 ObjectCache (MemoryCache.Default) 中,并通过 Repository 类公开。链条是这样的:

private Dictionary<string, T> itemsDictionary;
    private Dictionary<string, T> ItemsDictionary
    {
        get
        {
            return itemsDictionary ?? (itemsDictionary = RepositoryLoader.Load());        
        }
    }

    private List<T> itemsList;
    private List<T> ItemsList
    {
        get
        {
            return itemsList ?? (itemsList = ItemsDictionary.Values.ToList());
        }
    }

    public List<T> All { get { return ItemsList; } }

RepositoryLoader.Load() - 这会将内存缓存中的项目缓存为字典...

我的问题是 - 正如您所看到的,它还通过 2 个缓存属性进行 - 它是否会造成内存消耗的重复? :) 有没有办法优化这条链?

【问题讨论】:

  • Values 属性已经是 ICollection&lt;T&gt;。您可以将其作为属性公开。你有什么理由想要它作为List&lt;T&gt; 吗?如果是这样,是什么?也许有更好的方法来解决这个问题。

标签: c# caching properties memorycache


【解决方案1】:

如果Tclass,同时拥有itemsDictionaryitemsList 意味着您有两个对相同内存位置的引用。假设每个项目都很大,例如复杂的对象,这可以忽略不计(每个项目 4 或 8 个字节,具体取决于您运行的是 32 位还是 64 位)。但是,如果项目是 structs,这意味着它们将被复制,并且您将使用双倍的内存。

如果内存使用是个问题,并且您在某些时候只需要ItemsList,您可能希望删除itemsList 字段并让属性即时生成它:

return ItemsDictionary.Values.ToList();

另一个选项,假设您可以控制 RepositoryLoader 功能,是编写一个 IDictionary&lt;,&gt; 实现,将其 Values 公开为,例如直接IReadOnlyList&lt;T&gt;,无需重新创建列表。

【讨论】:

  • 感谢您的回答!是的,T 是一个类(不是结构)。您能否指导我参考 IReadonlyList 上的一些示例以了解我的上下文?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2019-08-12
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2016-05-25
  • 2014-02-05
相关资源
最近更新 更多