为什么与c#字典插入相比,std :: map插入这么慢?

时间:2019-05-31 14:09:29

标签: c# c++ performance dictionary stdmap

我正在将我的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;
}

为什么会有这样的区别?要获得相同的结果,应该有什么等效的替代方法?

1 个答案:

答案 0 :(得分:2)

在这里加两分钱。

C#字典是HashMap,但是C ++ std :: map是红黑树。 HashMap的性能优于树。如果要在c ++中使用HashMap,请使用std :: unordered_map。

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