C# 这是内存管理方面的最佳链吗?

C# 这是内存管理方面的最佳链吗?,c#,caching,properties,memorycache,C#,Caching,Properties,Memorycache,我们有一个将C#poco对象加载到内存中的系统。(从磁盘上的数据源反序列化)。它们进一步缓存在ObjectCache(MemoryCache.Default)中,并通过存储库类公开。链条是这样的: private Dictionary<string, T> itemsDictionary; private Dictionary<string, T> ItemsDictionary { get { re

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

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; } }
私有字典项字典;
专用词典项词典
{
得到
{
返回itemsDictionary???(itemsDictionary=RepositoryLoader.Load());
}
}
私人物品清单;
私有列表项目列表
{
得到
{
返回itemsList??(itemsList=ItemsDictionary.Values.ToList());
}
}
公共列表所有{get{return ItemsList;}}
RepositoryLoader.Load()-这会将内存缓存中的项缓存为字典


我的问题是——正如您所看到的,它还通过2个缓存属性进行处理——它是否会在内存消耗上创建复制?:)有没有办法优化此链?

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

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

return ItemsDictionary.Values.ToList();

另一种选择是,假设您可以控制
RepositoryLoader
功能,则编写一个实现,将其
公开为,例如,直接公开,而不重新创建列表。

属性已经是
ICollection
。你可以把它作为一个属性公开。是否有理由将其作为
列表
?如果是,什么?也许有更好的办法。谢谢你的回答!是的,T是一个类(不是struct)。您能为我的上下文介绍一下IReadonlyList上的一些示例吗?