I have a generic Dictionary that I am using as a cache in a threaded .NET project (C#). I will be doing a lot of reads on the dictionary (potentially hundreds or more per second at peak times).
I have a simple Get(int id) method that should return a CustomObject if it’s in the cache, or null otherwise.
My question:
Is it faster/more efficient to lock the dictionary, or just use a try/catch block?
Assuming the dictionary is stored in a variable named “dic”.
Lock Sample:
public CustomObject Get(int id)
{
lock(dic)
{
if (dic.ContainsKey(id))
return dic[id];
}
return null;
}
Try/Catch Sample:
public CustomObject Get(int id)
{
try
{
return dic[id];
}
catch
{
return null;
}
}
I think you should test it in your own environment. Basically:
So now the question is, how often you expect to have cache-miss, and therefore get an exception thrown. I would go for lock() as it’s execution time is not dependent on whether you will or not get cache-hit, which means it’s more predictable and measurable, while still – very cheap. I don’t think that hundreds hits per second would be any problem.
Simple tests I’ve made indicate, that getting cache-miss with try/catch is very, very expensive.
Edit:
Simple test shows that:
Which means, got for lock(), because it’s more efficient then try/catch if you’re getting more then 1 cache miss per few thousands tries, and it’s much more stable, being not depended on luck.