SortedList 、SortedDictionary、Dictionary元素添加耗时对比
public void DoTest()
{
Stopwatch sw = new Stopwatch();
sw.Start();
SortedDictionary<int, int> sdt = new SortedDictionary<int, int>();
sdt.Add(4, 1);
sdt.Add(6, 2);
sdt.Add(5, 3);
sdt.Add(3, 4);
sdt.Add(2, 5);
sdt.Add(9, 6);
sdt.Add(1, 7);
print(sdt);
Console.WriteLine($"-------------------------{sw.ElapsedTicks}----------------------------");
sw.Restart();
Dictionary<int, int> sdt1 = new Dictionary<int, int>();
sdt1.Add(4, 1);
sdt1.Add(6, 2);
sdt1.Add(5, 3);
sdt1.Add(3, 4);
sdt1.Add(2, 5);
sdt1.Add(9, 6);
sdt1.Add(1, 7);
print(sdt1);
Console.WriteLine($"-------------------------{sw.ElapsedTicks}----------------------------");
sw.Restart();
SortedList<int, int> sl = new SortedList<int, int>();
sl.Add(4, 1);
sl.Add(6, 2);
sl.Add(5, 3);
sl.Add(3, 4);
sl.Add(2, 5);
sl.Add(9, 6);
sl.Add(1, 7);
print(sl);
Console.WriteLine($"-------------------------{sw.ElapsedTicks}----------------------------");
sw.Stop();
}
void print<K,V>(IDictionary<K,V> dic)
{
foreach (var item in dic)
{
Console.WriteLine($"{item.Key}---------{item.Value}");
}
}
输出结果:
1---------7
2---------5
3---------4
4---------1
5---------3
6---------2
9---------6
-------------------------17616----------------------------
4---------1
6---------2
5---------3
3---------4
2---------5
9---------6
1---------7
-------------------------197----------------------------
1---------7
2---------5
3---------4
4---------1
5---------3
6---------2
9---------6
-------------------------5745----------------------------