private Obj CacheSomething()
{
Obj retVal = (Obj)System.Web.HttpRuntime.Cache["key"];
if (retVal == null)
{
retVal = new Obj();
System.Web.HttpRuntime.Cache["key"] = retVal;
}
return retVal;
}
This is probably a stupid question but is it stored in Server memory or client memory?
Also, what is the difference between doing the above and using a Singleton?
for example:
myObj= GenericSingleton<Obj>.GetInstance();
and
myObj= CacheSomething();
When I declare a new object every time it takes longer obviously, but both the above methods are faster than not caching and not using a singleton. Is using a singleton basically caching?
System.Web.HttpRuntime.Cacheis server-side.When using a
Singletonpattern you usually write code expecting the singleton instance to exist. With cached item you can never rely on its existence and should write code accordingly. For example, ifretValcreation is a time/resource consuming, you shouldlockto prevent other threads doing the same work of constructing it.