harish kapoor
harish kapoor

Reputation:

c# how hashtable shrinks when elements are removed from hashtable?

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

Regards Harish

Upvotes: 1

Views: 915

Answers (3)

Paul Sonier
Paul Sonier

Reputation: 39480

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.

Upvotes: 4

Joel Coehoorn
Joel Coehoorn

Reputation: 415725

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

Upvotes: 1

Jason Z
Jason Z

Reputation: 13422

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.

Upvotes: 0

Related Questions