【问题标题】:Why is the std::map insertion so slow compared to c# Dictionary insertion?与 c# 字典插入相比,为什么 std::map 插入这么慢?
【发布时间】:2019-05-31 14:09:28
【问题描述】:

我正在将我的 C# 库转换为 C++。我在整个应用程序中使用了一个 C# Dictionary 变量,当我尝试在两种情况下都使用std::map 而不是字符串作为键时,我感觉到性能上的巨大差异。

使用以下代码,C# Dictionary 耗时 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++版本的?您使用什么优化标志?
  • 请注意,您使用的是分辨率为 1 秒的time_t。当我尝试它时,我得到了结果 1。
  • 不是答案,而是tm* timetr2 = new tm(); -> tm timetr2;。更好地使用std::chrono::high_resolution_clock 来测量时间。
  • map&lt;int, int&gt; 更好,这样您就不会意外测试字符串性能。
  • 你会想看std::to_string(i),那将是malloc 100000 次。

标签: c# c++ performance dictionary stdmap


【解决方案1】:

在这里加上我的两分钱。

C# 字典是 HashMap,但 C++ std::map 是红黑树。 HashMap 比树表现更好。如果你想在c++中使用HashMap,请使用std::unordered_map。

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

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多