为什么 std::map 插入与 c# 字典插入相比这么慢?
Why is the std::map insertion so slow compared to c# Dictionary insertion?
我正在将我的 C# 库转换为 C++。我在整个应用程序中使用 C# 字典变量,当我尝试在两种情况下使用 std::map
而不是字符串作为键时,我感到性能有很大差异。
C# 字典使用以下代码花费了 0.022717 秒。 C++ 映射大约需要 3 秒。
C# 字典:
Stopwatch stopWatch = new Stopwatch();
Dictionary<string, int> dict = new Dictionary<string, int>();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
{
dict.Add(i.ToString(), i);
}
stopWatch.Stop();
var op = stopWatch.Elapsed.TotalSeconds.ToString();
C++ 映射:
#include <iostream>
#include <map>
#include <string>
#include <chrono>
using namespace std;
int main()
{
std::map<std::string, int> objMap;
tm* timetr = new tm();
time_t t1 = time(NULL);
localtime_s(timetr, &t1);
for (size_t i = 0; i < 100000; i++)
{
objMap.emplace(std::to_string(i), i);
}
tm* timetr2 = new tm();
time_t t2 = time(NULL);
localtime_s(timetr2, &t2);
time_t tt = t2 - t1;
cout << tt;
string sss = "";
cin >> sss;
}
为什么会有这样的差异?达到相同结果的等效替代方案应该是什么?
在这里加上我的两分钱。
C#字典是一个HashMap,而C++std::map是一个Red-Black树。 HashMap 的性能优于树。如果要在c++中使用HashMap,请使用std::unordered_map.
不确定 100% 是这个原因,但是你可以在切换到 std::unordered_map 后找到它。
我正在将我的 C# 库转换为 C++。我在整个应用程序中使用 C# 字典变量,当我尝试在两种情况下使用 std::map
而不是字符串作为键时,我感到性能有很大差异。
C# 字典使用以下代码花费了 0.022717 秒。 C++ 映射大约需要 3 秒。
C# 字典:
Stopwatch stopWatch = new Stopwatch();
Dictionary<string, int> dict = new Dictionary<string, int>();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
{
dict.Add(i.ToString(), i);
}
stopWatch.Stop();
var op = stopWatch.Elapsed.TotalSeconds.ToString();
C++ 映射:
#include <iostream>
#include <map>
#include <string>
#include <chrono>
using namespace std;
int main()
{
std::map<std::string, int> objMap;
tm* timetr = new tm();
time_t t1 = time(NULL);
localtime_s(timetr, &t1);
for (size_t i = 0; i < 100000; i++)
{
objMap.emplace(std::to_string(i), i);
}
tm* timetr2 = new tm();
time_t t2 = time(NULL);
localtime_s(timetr2, &t2);
time_t tt = t2 - t1;
cout << tt;
string sss = "";
cin >> sss;
}
为什么会有这样的差异?达到相同结果的等效替代方案应该是什么?
在这里加上我的两分钱。
C#字典是一个HashMap,而C++std::map是一个Red-Black树。 HashMap 的性能优于树。如果要在c++中使用HashMap,请使用std::unordered_map.
不确定 100% 是这个原因,但是你可以在切换到 std::unordered_map 后找到它。