First off, let me wish everyone a Happy New Year and the best of luck with those millions of New Year's resolutions which seem to be flying around the place. I'm sure the cloud tag over at 43things is dominated by subjects related to weight loss/fitness/all that good stuff. My own commitment for work is to continue searching for better ways to do things: whether it's coding, planning, or our daily game of foosball. I'd like to make a commitment to blog twice a week, but unless I stumble across a fountain of ideas, that seems unlikely.
I'm currently working on a class that needs to store unique information, so naturally I've got a Dictionary tucked away with a couple of accessor methods. While writing my tests, I decided that returning 0 for non-existent values rather than throwing would be more appropriate. So, I punched in the following test and then made it pass.
public void RetrievingANonExistentStatisticReturnsZero()
Campaign c = new Campaign();
double value = c.GetStatistic("non-existent");
The first implementation I wrote for
Dictionary.ContainsKey() and then I immediately wondered if
TryGetValue() would be any faster. After all, the MSDN docs say they both approach O(1).
Remembering my experience with enums, I whipped up another small benchmark. This time, though, there was only a minute difference, so I'm sticking with the
ContainsKey version. It's tough being so curious at times 😉