为什么 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 是一棵红黑树。HashMap 的性能比树更好。如果你想在 c++ 中使用 HashMap,请使用 std::unordered_map。
不确定 100% 这是原因,但您可以在切换到 std::unordered_map 后找到它。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- 缓慢提升ASIO
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 为什么 std::map 插入与 c# 字典插入相比如此缓慢
- 散列映射快速插入但检索缓慢
- QAbstractItemModel:为什么在模型中插入大量项目时发出dataChanged和insert行信号如此缓慢
- 为什么我插入到STL列表运行缓慢