Happy New Year! Now back to work :)


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.

[Test]
public void RetrievingANonExistentStatisticReturnsZero()
{
Campaign c = new Campaign();

double value = c.GetStatistic("non-existent");

Assert.AreEqual(0, value);
}

The first implementation I wrote for GetStatistic() used 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 😉

Comments (2)
  1. bradwils says:

    They both approach O(1) assuming a good hashing function, but the point of TryGetValue() is to only execute that O(1) algorithm once. If you use ContainsKey() and then the indexer, you’re doing that same O(1) operation twice.

    And, in fairness, it almost never matters. 🙂 But the syntax of TryGetValue() is useful enough that I tend to up using it anyway.

  2. Casper says:

    What you’re saying definitely makes sense, but I should have been a bit clearer in my last paragraph: TryGetValue() appeared to be slightly slower when I did the benchmarking.

    Maybe I should have tried more than ten million iterations per test, but this was a quick-‘n-dirty thing.

Comments are closed.

Skip to main content