我认为在添加和删除元素时,ImmutableList比List慢得多。是吗?
基准。添加和删除ImmutableList的Perforamce是好的。 RemoveAt甚至比List更快。
static void Main(string[] args)
{
// Generic List Test
var genericList = new List<int>();
var sw = Stopwatch.StartNew();
for (int i = 0; i < 20000; i++)
{
genericList.Add(i);
}
sw.Stop();
Console.WriteLine("Add duration for List<T>: " + sw.ElapsedMilliseconds);
IList<int> completeList = new List<int>(genericList);
sw.Restart();
// Remove from 20000 -> 0.
for (int i = completeList.Count - 1; i >= 0; i--)
{
genericList.RemoveAt(0);
}
sw.Stop();
Console.WriteLine("Remove duration for List<T>: " + sw.ElapsedMilliseconds);
Console.WriteLine("Items after remove for List<T>: " + genericList.Count);
// ImmutableList Test
var immutableList = ImmutableList<int>.Empty;
sw.Restart();
for (int i = 0; i < 20000; i++)
{
immutableList = immutableList.Add(i);
}
sw.Stop();
Console.WriteLine("Add duration for ImmutableList<T>: " + sw.ElapsedMilliseconds);
sw.Restart();
// Remove from 20000 -> 0.
for (int i = completeList.Count - 1; i >= 0; i--)
{
immutableList = immutableList.RemoveAt(0);
}
sw.Stop();
Console.WriteLine("Remove duration for ImmutableList<T>: " + sw.ElapsedMilliseconds);
Console.WriteLine("Items after remove for ImmutableList<T>: " + immutableList.Count);
}
结果
Add duration for List<T>: 0
Remove duration for List<T>: 37
Items after remove for List<T>: 0
Add duration for ImmutableList<T>: 22
Remove duration for ImmutableList<T>: 14
Items after remove for ImmutableList<T>: 0
答案 0 :(得分:3)
老实说,不变性意味着缺乏表现。
我希望使用不可变列表可以更快地执行许多操作。
不可变列表的实现使用二叉搜索树,与搜索,插入和删除的数组相比,它具有良好的性能特征。将这些因素复制到游戏中仍然存在开销。因此,将有一个临界点,其中一个将比另一个表现更好。
我的机器上的删除结果(不可变/常规)毫秒
Deletes 100 1000 10000 100000
Count
1000 4/0 na na na
10000 4/0 5/1 na na
1e5 4/2 5/23 22/215 na
1e6 7/44 8/431 37/4676 118/44081
1e7 8/718 7/7363 36/77638 110/x*
1e8 8/7594 9/76200 31/781349 113/x*
* I didn't have the patience to finish benchmarking here.
答案 1 :(得分:-3)