Dictionary vs. Hashtable (C# 2.0)

A

Anders Borum

Hello!

I am using Hashtables to cache data in services and am looking at generics
for typed access (I control the key/value types). However, I was surprised
to see that the Dictionary throws a KeyNotFoundException if you try to
reference missing keys, which is a change from the Hashtable.

So what?

Well, the idea of a cache is to ensure high performance (low latency) access
to your data, and wrapping "if" statements around each "get" call sounds
expensive. I like the typed access to my cache, but dislike the overhead ..
(not sure whether the Hashtable implementation calls .ContainsKey internally
before returning null / value).

// Typed version (dictionary) - the ContainsKey method is another
// member I've implemented
public CmsObjectNode GetItem(Guid key)
{
return (this.ContainsKey(key)) ? this.cmsObjectNodeCache[key] : null;
}

// Untyped version (hashtable)
public CmsObjectNode GetItem(Guid key)
{
return this.cmsObjectNodeCache[key] as CmsObjectNode;
}

Your comments?

Thanks in advance!
 
N

Nicholas Paldino [.NET/C# MVP]

Anders,

Why not just derive from Dictionary<TKey, TValue> and then add a new
method? Something like this:

public TValue GetValue(TKey key)
{
// Check for existence here.
if (this.ContainsKey(key))
{
// Return the value.
return this[key];
}

// The key does not exist, return the default.
return default(T);
}

The problem with this is that it is valid in a Dictionary to have null
as a value corresponding to a key. The dictionary is more correct in that
sense.

You are right, using the if statement might incur an extra overhead, but
I wouldn't think that it is that much. Have you tried to use the check
against ContainsKey, and then measure the performance to see if you are
truly impacted by it?

Hope this helps.
 
M

Mattias Sjögren

Anders,
However, I was surprised
to see that the Dictionary throws a KeyNotFoundException if you try to
reference missing keys, which is a change from the Hashtable.

It has to since TValue may be a non-nullable value type. And simply
returning default(TValue) may not always be appropriate.

But since you know that the dictionary contains CmsObjectNode objects,
you can write

public CmsObjectNode GetItem(Guid key)
{
CmsObjectNode node;
return cmsObjectNodeCach.TryGetValue(key, out node) ? node : null;
}


Mattias
 
A

Anders Borum

Hello!

Sorry for the long delay since my posting - life caught me.

I would like to thank you for your helpful replies. Regarding a performance
test comparing the Dictionary vs. Hashtable performance using .Contains() to
validate for the presense of keys, I am working on a small sample and will
post the findings here shortly.

Again, thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top