views:

511

answers:

3

Hi, I am looking to find out the logic , if any , which shrinks hashtable in c# when elements are removed from it.

Regards Harish

A: 

The only indication of size changes for a hashtable in the documentation is when the load factor is exceeded and the size of the hashtable is increased. There is no mention of a hastable ever shrinking.

There is some further detail of the load factor on MSDN.

Jason Z
A: 

As an aside, since you're using .net2.0 or later you should probably use a Dictionary<K,V> rather than a HashTable.

Joel Coehoorn
+4  A: 

c# hashtables don't shrink; they only grow. The logic is important, because the rehashing algorithm is VERY expensive to run; for most situations, the space saved by rehashing into a smaller hashtable would be completely overrun by the cost of the rehashing. Particularly on an automatic basis, where any removals from the hashtable may not be the "last" removal (impossible to tell from within the hashtable on an algorithmic basis), the potential value is simply not worth it.

If your hashtable shrinks significantly, and you'd really like to reclaim the space, I recommend simply creating a new one (with the right size) and copying the elements over to it.

McWafflestix