假设下面这段代码缓存了两个对象集合MyObject
:一个集合是类型IEnumerable<MyObject>
的,另一个是类型的List<MyObject>
。代码从缓存中检索值,然后访问集合:
class Program
{
static void Main(string[] args)
{
CacheManager.CacheSomething();
}
public class MyService
{
private IEnumerable<AnObject> AnObjects
{
get
{
return new[]
{
new AnObject {MyString1 = "one", MyString2 = "two"},
new AnObject {MyString1 = "three", MyString2 = "four"}
};
}
}
public IEnumerable<AnObject> GetEnumerable()
{
return AnObjects;
}
public List<AnObject> GetList()
{
// Run it out to a list
return AnObjects.ToList();
}
}
public static class CacheManager
{
public static void CacheSomething()
{
// Get service
var service = new MyService();
// Get the values as List and Enumerable
var list = service.GetList();
var enumerable = service.GetEnumerable();
// Putting them in a cache
HttpRuntime.Cache.Insert("list", list);
HttpRuntime.Cache.Insert("enumerable", enumerable);
// Get the values
var retrievedList = HttpRuntime.Cache["list"] as List<AnObject>;
var retrievedEnumerable = HttpRuntime.Cache["enumerable"] as IEnumerable<AnObject>;
// Access both
var res1 = retrievedList.ToList();
var res2 = retrievedEnumerable.ToList();
}
}
public class AnObject
{
public string MyString1 { get; set; }
public string MyString2 { get; set; }
}
}
根据集合类型存储这些对象所需的内存量是否存在差异?
我问的原因是,当我们分析我们的应用程序时,我们注意到当我们查看依赖关系树时,IEnumerable
有与之关联的服务。这是否意味着它也缓存服务?
任何人都可以阐明这是否值得关注吗?将一个存储IEnumerable
在缓存中是否有问题?我们应该更喜欢缓存List
s 而不是IEnumerable
s 吗?