On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.