0

根据数据大小,我大致有两类不同的数据缓存要求:1) 非常小的数据(2-30 个字符)——这包括给定 entityId 的类型代码等内容。该系统基于父子实体层次结构的概念,并且根据与实体类型代码组合构建的值授权操作。为不同的实体缓存这些类型代码可以节省 db fetch 的时间。2) 中/大数据——这是一般数据,如产品描述和页面。

我对哪种方法更适合第一类数据感到困惑。我可以像这样缓存它:

HttpRuntime.Cache.Insert("typeCode" + entityId, entityTypeCode);

或像这样:

Dictionary<int, string> etCodes = 
    (Dictionary<int, string>)HttpRuntime.Cache["typeCode"];
etCodes[entityId] = entityTypeCode;

显然,在第二种方法中,我为每个 entityId 节省了不必要的缓存项。或者,让 Cache 对象填充几个如此小的项目是可以的。

就性能和开销而言,这些方法中哪一种更好?

4

1 回答 1

0

就我个人而言,我会采用您对单个对象的第二种方法,并使用自定义对象而不是Dictionary.

这将使我能够在以后控制更多方面,例如对象内项目的到期或更改实现。

我会这样做:

public class MyCacheObject
{
    public static MyCacheObject 
    {
        get
        {   
            // ...Omitted locking here for simplification...

            var o = HttpRuntime.Cache["MyCacheObject] as MyCacheObject;
            if ( o = null )
            {
                o = new MyCacheObject();
                HttpRuntime.Cache["MyCacheObject] = o;
            }
            return o;
        }
    }

    public object GetEntity( string id, string code )
    {
        // ...
    }

    public void SetEntity( object entity, string id, string code )
    {
        // ...
    }

    // ...
}

如果您有实体的自定义基类,则可以进一步优化GetEntity和方法。SetEntity

于 2011-05-28T18:57:06.927 回答