It’s common for programmer’s to cache data in order to improve performance. Constantly reading data from a database or file can be very resource intensive and can significantly slow down a website. I need to remember however that there is no guarantees on what will stay in the cache and what will be pushed out. Obviously I never use the cache to hold data which is not saved in a permanent location, otherwise when the memory fills up that data may be lost forever, but often I see code like this:
Object GetData()
{
if (cache["MyData"] != null)
{
return cache["MyData"];
}
else
{
cache["MyData"] = GetDataFromSource();
return cache["MyData"];
}
}
If the website gets enough traffic this code can throw an error, it should have been written:
Object GetData()
{
if (cache["MyData"] != null)
{
return cache["MyData"];
}
else
{
Object data = GetDataFromSource();
cache["MyData"] = data;
return data;
}
}