【发布时间】:2010-12-26 05:59:07
【问题描述】:
这是我一直在调查的一个好奇心。在我一直运行的测试中,与 STL unordered_map 相比,.NET Dictionary 类的执行速度快得离谱,我不知道为什么。
(在我的机器上为 0.5 秒与 4 秒) (.NET 3.5 SP1 与 Visual Studio 2008 Express SP1 的 STL)
另一方面,如果我用 C# 和 C++ 实现自己的哈希表,C++ 版本的速度大约是 C# 版本的两倍,这很好,因为它强化了我的常识,即本机机器代码有时更快。 (见。我说“有时”。)我在两种语言中都是同一个人,我想知道微软的 C# 编码器有什么技巧可以玩微软的 C++ 编码器不能?我很难想象编译器如何自己发挥这些技巧,并经历优化应该看起来是任意函数调用的麻烦。
这是一个简单的测试,存储和检索整数。
C#:
const int total = (1 << 20);
int sum = 0;
Dictionary<int, int> dict = new Dictionary<int, int>();
for(int i = 0; i < total; i++)
{
dict.Add(i, i * 7);
}
for(int j = 0; j < (1 << 3); j++)
{
int i = total;
while(i > 0)
{
i--;
sum += dict[i];
}
}
Console.WriteLine(sum);
C++:
const int total = (1 << 20);
int sum = 0;
std::tr1::unordered_map<int, int> dict;
for(int i = 0; i < total; i++)
{
dict.insert(pair<int, int>(i, i * 7));
}
for(int j = 0; j < (1 << 3); j++)
{
int i = total;
while(i > 0)
{
i--;
std::tr1::unordered_map<int, int>::const_iterator found =
dict.find(i);
sum += found->second;
}
}
cout << sum << endl;
【问题讨论】:
-
C++ 版本的类型是否像 Dictionary
那样? -
本机机器码比什么快?你认为 C# 的运行方式是什么?
-
你如何衡量性能?
-
好奇你是否在发布版本中运行代码。由于要执行大量额外检查,MS STL 实现在调试构建中的速度非常慢。
-
@imaginaryboy,MS 并不是唯一一个遭受这种痛苦的人。使用 XCode 从 Debug 切换到 Release 几乎使上述 C++ 代码的性能提高了一倍。
标签: c# c++ performance hashtable