【发布时间】:2013-08-15 08:08:40
【问题描述】:
我的印象是在字典中查找项目比在列表中查找项目更快,以下代码似乎暗示了其他情况:
字典:66 记号
列表:32 个滴答声
我假设我在某个地方搞砸了?
static void Main(string[] args)
{
// Speed test.
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"P1I1-1MS P2I1-1MS 3I-1MS 4I-1MS", 2},
{"P1I2-1MS P2I1-1MS 3I-1MS 4I-1MS", 1},
{"P1I3-1MS P2I1-1MS 3I-1MS 4I-1MS", 0},
{"P1I4-1MS P2I1-1MS 3I-1MS 4I-1MS", -1},
{"P1I5-1MS P2I1-1MS 3I-1MS 4I-1MS", 0},
{"P1I1-1MS P2I2-1MS 3I-1MS 4I-1MS", 0},
{"P1I2-1MS P2I2-1MS 3I-1MS 4I-1MS", 0},
{"P1I3-1MS P2I2-1MS 3I-1MS 4I-1MS", 0},
{"P1I4-1MS P2I2-1MS 3I-1MS 4I-1MS", 0},
{"P1I5-1MS P2I2-1MS 3I-1MS 4I-1MS", 0},
{"P1I1-1MS P2I3-1MS 3I-1MS 4I-1MS", 0},
{"P1I2-1MS P2I3-1MS 3I-1MS 4I-1MS", 0},
{"P1I3-1MS P2I3-1MS 3I-1MS 4I-1MS", 0},
{"P1I4-1MS P2I3-1MS 3I-1MS 4I-1MS", 0},
{"P1I5-1MS P2I3-1MS 3I-1MS 4I-1MS", 0},
{"P1I1-1MS P2I4-1MS 3I-1MS 4I-1MS", 2}
};
List<string> l = new List<string>();
l.Add("P1I1-1MS P2I1-1MS 3I-1MS 4I-1MS");
l.Add("P1I2-1MS P2I1-1MS 3I-1MS 4I-1MS");
l.Add("P1I3-1MS P2I1-1MS 3I-1MS 4I-1MS");
l.Add("P1I4-1MS P2I1-1MS 3I-1MS 4I-1MS");
l.Add("P1I5-1MS P2I1-1MS 3I-1MS 4I-1MS");
l.Add("P1I1-1MS P2I2-1MS 3I-1MS 4I-1MS");
l.Add("P1I2-1MS P2I2-1MS 3I-1MS 4I-1MS");
l.Add("P1I3-1MS P2I2-1MS 3I-1MS 4I-1MS");
l.Add("P1I4-1MS P2I2-1MS 3I-1MS 4I-1MS");
l.Add("P1I5-1MS P2I2-1MS 3I-1MS 4I-1MS");
l.Add("P1I1-1MS P2I3-1MS 3I-1MS 4I-1MS");
l.Add("P1I2-1MS P2I3-1MS 3I-1MS 4I-1MS");
l.Add("P1I3-1MS P2I3-1MS 3I-1MS 4I-1MS");
l.Add("P1I4-1MS P2I3-1MS 3I-1MS 4I-1MS");
l.Add("P1I5-1MS P2I3-1MS 3I-1MS 4I-1MS");
l.Add("P1I1-1MS P2I4-1MS 3I-1MS 4I-1MS");
Stopwatch sw = new Stopwatch();
string temp = "P1I1-1MS P2I4-1MS 3I-1MS 4I-1MS";
bool inDictionary = false;
sw.Start();
if (d.ContainsKey(temp))
{
sw.Stop();
inDictionary = true;
}
else sw.Reset();
Console.WriteLine(sw.ElapsedTicks.ToString());
Console.WriteLine(inDictionary.ToString());
bool inList = false;
sw.Reset();
sw.Start();
if (l.Contains(temp))
{
sw.Stop();
inList = true;
}
else sw.Reset();
Console.WriteLine(sw.ElapsedTicks.ToString());
Console.WriteLine(inList.ToString());
Console.ReadLine();
}
编辑
修改 Matthew Watson 的代码。
【问题讨论】:
-
您是在调试器还是可执行文件中运行此测试?那么模式,调试/发布呢?
-
是的,它正在调试器(调试)中运行。 .net 4 客户端配置文件
-
Bad idea,你也应该在发布模式下运行它。
-
一个执行和案例很少提供有效数据。您应该运行搜索 10k 次并让它搜索不同的匹配项。您的匹配长度都相同,并且包含许多相同的数据,这可能会减少一些字典的好处。
-
@HansRudel 我刚刚在发布版中运行了测试,而不是在调试器中运行了超过 1000000 次迭代,字典肯定更快:
Dict: 97628.10ns vs List: 10396.84ns虽然差别不大。我怀疑这是由于每个集合的大小相对较小。
标签: c# performance list c#-4.0 dictionary