Welcome to MSDN Blogs Sign in | Join | Help
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 ;)

Posted: Thursday, January 04, 2007 8:23 AM by casper
Filed under:

Comments

bradwils said:

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.

# January 4, 2007 11:13 AM

casper said:

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.

# January 5, 2007 2:17 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker