【发布时间】:2018-06-27 21:05:46
【问题描述】:
假设下面这段代码缓存了两个对象集合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 是否有问题?我们是否应该更喜欢缓存Lists 而不是IEnumerables?
【问题讨论】:
-
如果您已经完成了所有这些的编写过程,为什么不更进一步,使用基准工具查看两者的性能以及它们的分配情况?
-
我刚刚花了我一天中最好的时间来调查这个问题,但我仍然没有具体的答案。想要证明这一点比您想象的要难。
标签: c# list caching ienumerable httpruntime.cache