Assuming the following piece of code that caches two collections of objects MyObject
: one collection is of type IEnumerable<MyObject>
and the other one is of type List<MyObject>
. The code retrieves the values from the cache and then accesses the collection:
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; }
}
}
Is there a difference in terms of the amount of memory required to store these objects based on the collection types?
The reason that I ask is that when we have been profiling our applications and we've noticed that when we look at the dependency tree, the IEnumerable
has the Service associated with it. Does that mean that it caches the service too?
Can anyone shed some light as to whether this is a cause for concern? Is it a problem to store an IEnumerable
in the cache? Should we prefer caching List
s over IEnumerable
s?