I have a situation where I have a large collection of items stored in HttpApplicationState
which internally uses a NameValueCollection
to store key-value pairs. By large I mean in the order of hundreds of thousands of string items. In this particular scenario I am also trying to do a batch removal of keys (again, removing large chunks of items by key from the collection) but I am finding that is painfully slow to do.
I wrote the following samples to compare. The first code sample uses a NameValueCollection
to remove all values by key:
NameValueCollection collection = new NameValueCollection();
// Setup
for (int i = 0; i < 100000; i++)
{
collection.Add(i.ToString(), i.ToString());
}
// Remove
for (int i = 0; i < 100000; i++)
{
collection.Remove(i.ToString());
}
Running this takes an age (in fact I gave up because it took too long). I then compared it with this version which uses a Dictionary<TKey, TValue>
:
Dictionary<int, int> collection = new Dictionary<int, int>();
// Setup
for (int i = 0; i < 100000; i++)
{
collection.Add(i, i);
}
// Remove
for (int i = 0; i < 100000; i++)
{
collection.Remove(i);
}
The above sample runs so fast it might as well be instant.
So why do two different collections that to me look to do similar things work so differently?