为什么 std::map 插入与 c# 字典插入相比如此缓慢

Why is the std::map insertion so slow compared to c# Dictionary insertion?

本文关键字:插入 缓慢 std map 为什么 字典      更新时间:2023-10-16

我正在将我的 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 是一棵红黑树。HashMap 的性能比树更好。如果你想在 c++ 中使用 HashMap,请使用 std::unordered_map。

不确定 100% 这是原因,但您可以在切换到 std::unordered_map 后找到它。