为什么我不能预分配HashSet的< T> [英] Why can't I preallocate a hashset<T>

查看:165
本文介绍了为什么我不能预分配HashSet的< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能预先分配一个的HashSet< T>

Why can't I preallocate a hashset<T>?

有几次,我可能是加入了很多元素,它的,我想消除大小调整。

There are times when i might be adding a lot of elements to it and i want to eliminate resizing.

推荐答案

有没有技术原因,这不应该是可能的 - 微软只是没有选择公开构造一个初始。容量

There's no technical reason why this shouldn't be possible - Microsoft just hasn't chosen to expose a constructor with an initial capacity.

如果你可以调用一个构造函数,需要一个的IEnumerable< T> 和使用的实施的ICollection< T> ,相信会用集合的大小作为初始最小容量。这是一个实现细节,你介意。容量仅需要足够大来存储所有不同的元素...

If you can call a constructor which takes an IEnumerable<T> and use an implementation of ICollection<T>, I believe that will use the size of the collection as the initial minimum capacity. This is an implementation detail, mind you. The capacity only has to be large enough to store all the distinct elements...

编辑:我认为,如果能证明是比它需要更大的方式是,当它结束找出多少个不同的元素存在的的构造函数将修剪多余的真正的是。

I believe that if the capacity turns out to be way larger than it needs to be, the constructor will trim the excess when it's finished finding out how many distinct elements there really are.

无论如何,如果你的有无的您要添加到集合中的的HashSet< T> 的它实现的ICollection< T> ,然后将它传递给构造函数,而不是一个添加的元素之一,将是一个双赢,基本上是:)

Anyway, if you have the collection you're going to add to the HashSet<T> and it implements ICollection<T>, then passing it to the constructor instead of adding the elements one by one is going to be a win, basically :)

编辑:一种解决方法是使用一个词典<的代替的HashSet< TKEY的,TValue> T> 和刚未使用的值。这不会在所有情况下的工作,虽然,因为它不会给你相同的接口的HashSet< T>

One workaround would be to use a Dictionary<TKey, TValue> instead of a HashSet<T>, and just not use the values. That won't work in all cases though, as it won't give you the same interface as HashSet<T>.

这篇关于为什么我不能预分配HashSet的&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆