问题描述
我听说.NET System.Collections.Immutable
集合被实现为平衡的二叉树,以满足其不变性约束,即使是传统上通过使用GetHashCode
的整数值对哈希表(如Dictionary
进行建模)的集合排序键.
I have heard that the .NET System.Collections.Immutable
collections are implemented as balanced binary trees in order to satisfy their immutability constraints, even collections which traditionally model hash tables like Dictionary
, by using the integral value of GetHashCode
as a sort key.
如果我有一种类型,对于它来说生成哈希码很便宜,并且对于它来说比较便宜(例如string
或int
),并且我不在乎我的排序方式集合,更喜欢ImmutableSortedDictionary
是否有意义,因为基础数据结构仍然是排序的?
If I have a type for which it is cheap to generate a hash code, and for which is cheap to compare (e.g. string
or int
), and I don't care about the sorted-ness of my collection, would it make sense to prefer ImmutableSortedDictionary
because the underlying data structure is sorted anyway?
推荐答案
答案是是,在某些情况下(例如,使用Int32
键)更喜欢ImmutableSortedDictionary
是有意义的.
The answer is yes, it can make sense to prefer ImmutableSortedDictionary
in certain conditions, for instance with Int32
keys.
就我而言,用Int32
键发现ImmutableSortedDictionary
是更好的选择.
In my case, with Int32
keys I found out that ImmutableSortedDictionary
was a better pick.
我已经使用一百万个项目运行了一个小型基准测试:
I have run a small benchmark using 1 million items:
- 按密钥的升序插入1,000,000个项目
- 更新1,000,000个随机物品
- 扫描1,000,000个项目,即对集合中的每个项目进行一次迭代
- 读取1,000,000个随机项目
- 删除1,000,000个随机项目
ImmutableDictionary< int,object>
Insert: 2499 ms
Update: 7275 ms
Scan: 385 ms
Read: 881 ms
Delete: 5037 ms
ImmutableSortedDictionary< int,object>
Insert: 1808 ms
Update: 4928 ms
Scan: 246 ms
Read: 732 ms
Delete: 3522 ms
ImmutableSortedDictionary
在所有操作上都比ImmutableDictionary
快一点.请注意,插入一次是按键的升序进行的(因为它恰好与我的特定用例匹配).
ImmutableSortedDictionary
is a bit faster than ImmutableDictionary
on all operations. Note that insertion was done one item at a time in ascending order of key (because it happens to match my particular use case).
但是,您还应该考虑使用具有某些锁定功能的可变集合.写入可变的Dictionary<int, object>
快一个数量级.
However, you should also consider using a mutable collection with some locking. Writing to a mutable Dictionary<int, object>
is one order of magnitude faster.
这篇关于应该选择ImmutableDictionary还是ImmutableSortedDictionary吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!