Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

Collection Performance Test

leave a comment »

Like most developers, we make extensive use of the .Net collection classes. But there are times where those classes seem like overkill. For example, if I needed to collect a unique set of strings then I could define a Dictionary<T, U>[^] class like “Dictionary<String, Object>”. This would allow me to see if the string already exists and if it doesn’t then I could add it.

This led me to the Power Collections for .Net[^] provided by Wintellect[^]. This library has a Set<T>[^] class, which would allow me to collect the unique strings without the extraneous mapped value. But like most things, I worry that performance will suffer.

So I decided to run some performance tests on both the .Net collection classes and the Power Collections. I’m not going to include my actual results here, but I have put together a sample project[^] so you can run the tests yourself.

When you run the tests you will see that the .Net collections classes perform better than the Power Collection classes. The project is setup to tests each collection with 1 million entries, but similar results occur when running with 100, 000 entries.

Another item to note, is that Dictionary<T, U> can perform better than a Hashtable[^] . The times for the common operations are almost identical, but the Hashtable does not have the TryGetValue[^] method. This means you must first verify that the value exists with the Contains method, then get the value. So basically, if you use a Hashtable you have to lookup an item twice. I’m assuming of course that you are not relying on exceptions to notify you that a key does not exist. Finally, with the Dictionary class you do not need to cast the Keys or Values to their actual type. So you save in performance there also.

Because I find that I need the Set<T> class from Power Collections often, I decided to write a wrapper around the .Net Dictionary<T, U> class. This makes the code easier to read, but I do not sacrifice performance. I’ve included this class in the sample project, which you are free to use as you see fit.

I do realize that the performance gains are not huge, but they can be significant depending on how they are used. In addition, the Power Collections offer a lot more types of Collections, so it is still very useful.


Written by Tom

June 18, 2007 at 4:10 pm

Posted in .Net, C#, Optimization

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: