【发布时间】:2010-03-04 02:12:13
【问题描述】:
我不明白为什么 SortedDictionary 的性能在设置和检索值方面比 Dictionary 慢大约 5 倍。我预计插入和删除会更慢,但不会更新或检索。我已经测试了 .Net 3.5 和 .Net 4.0 版本的编译代码。预先计算了一组随机密钥,以确保随机变化不会导致随机访问的差异。
以下是测试的场景。
- 使用 [key] 访问器顺序更新每个值
- 使用 [key] 访问器顺序访问每个值
- 使用 TryGetValue 顺序访问每个值
- 使用 [key] 访问器随机访问每个值
- 使用 TryGetValue 随机访问每个值
有人知道为什么会出现性能差异吗?
如果我做错了什么或愚蠢的,请指出。
示例代码:只需使用 SortedDictionary 切换字典即可测试差异。
const int numLoops = 100;
const int numProperties = 30;
const int numInstances = 1000;
static void DictionaryBench(int numLoops, int numValues, int numInstances, string[] keyArray)
{
Stopwatch sw = new Stopwatch();
double total = 0.0d;
for (int j = 0; j < numLoops; j++)
{
//sw.Start();
Dictionary<string, object> original = new Dictionary<string, object>(numValues);
for (int i = 0; i < numValues; i++)
{
original.Add(String.Format("Key" + i.ToString()), "Value0:" + i.ToString());
}
List<Dictionary<string, object>> collectionList = new List<Dictionary<string, object>>(numInstances);
for (int i = 0; i < numInstances; i++)
{
collectionList.Add(new Dictionary<string, object>(original));
}
sw.Start();
//Set values on each cloned instance to uniqe values using the same keys
for (int k = 0; k < numInstances; k++)
{
for (int i = 0; i < numValues; i++)
{
collectionList[k]["Key" + i.ToString()] = "Value" + k.ToString() + ":" + i.ToString();
}
}
//Access each unique value
object temp;
for (int k = 0; k < numInstances; k++)
{
for (int i = 0; i < numValues; i++)
{
temp = collectionList[k]["Key" + i.ToString()];
}
}
//Random access
//sw.Start();
for (int k = 0; k < numInstances; k++)
{
for (int i = 0; i < numValues; i++)
{
collectionList[k].TryGetValue(keyArray[i],out temp);
}
}
sw.Stop();
total += sw.ElapsedMilliseconds;
sw.Reset();
}
【问题讨论】: