为什么 ImmutableList<T> 的枚举器与 List<T> 相比慢得多
Why is ImmutableList<T>'s enumerator so much slower compared to List<T>
我有一段代码经常迭代一个小列表。鉴于该列表在运行时从不更改,我将实现替换为 ImmutableList<T>
。查看 dotTrace 的性能跟踪,这比正常的 List<T>
:
表现差得多
(左边List<T>
,右边ImmutableList<T>
)
为什么会发生这种情况,是否有解决方法?
与 List<T>
不同,后者环绕一个根据需要调整大小的数组,ImmutableList<T>
在内部使用不可变的 AVL tree (see Channel9 video discussing this).
那么我怎样才能使用不可变集合实现这一点呢?
引用 .NET Framework blog post 关于不可变集合的内容
Reasons to use immutable array:
- Updating the data is rare or the number of elements is quite small (<16)
- you need to be able to iterate over the data in performance critical sections
- you have many instances of immutable collections and you can’t afford keeping the data in trees
Reasons to stick with immutable list:
- Updating the data is common or the number of elements isn’t expected to be small
- Updating the collection is more performance critical than iterating the contents
我有一段代码经常迭代一个小列表。鉴于该列表在运行时从不更改,我将实现替换为 ImmutableList<T>
。查看 dotTrace 的性能跟踪,这比正常的 List<T>
:
List<T>
,右边ImmutableList<T>
)
为什么会发生这种情况,是否有解决方法?
与 List<T>
不同,后者环绕一个根据需要调整大小的数组,ImmutableList<T>
在内部使用不可变的 AVL tree (see Channel9 video discussing this).
那么我怎样才能使用不可变集合实现这一点呢?
引用 .NET Framework blog post 关于不可变集合的内容
Reasons to use immutable array:
- Updating the data is rare or the number of elements is quite small (<16)
- you need to be able to iterate over the data in performance critical sections
- you have many instances of immutable collections and you can’t afford keeping the data in trees
Reasons to stick with immutable list:
- Updating the data is common or the number of elements isn’t expected to be small
- Updating the collection is more performance critical than iterating the contents