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 Lists over IEnumerables?
Difference in amount of memory? No.
Why?
IEnumerableis not a type; it's an interface. That means that anything stored in anIEnumerableis actually some other type that implementsIEnumerable(likeList, for example).IEnumerableonly forces implementation of methods to read the list. It's not appropriate for modifying the collection. That's why you would want to cast it to the actual type (likeList), so you can use methods likeAdd.