gpt4 book ai didi

c++ - C++ std::unordered_map 对比 Kotlin/Java HashMap 的性能

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:13 25 4
gpt4 key购买 nike

我创建了 Andorid 项目来测量一些等效的代码,而这个项目让我陷入了困境,为什么?为什么 C++ 在这里慢了 3 倍?

我已经对 C++ 进行了一些调整,因为立即尝试放置,然后 push_back 比当前方法慢,但仍然如此。这里的复杂性应该是相同的,对吧?

Kotlin:139,945,691 ns(139 毫秒)

C++:347,100,764 ns(347 毫秒)

Kotlin

data class Record(
val year: Int,
val month: Int,
val day: Int,
var temperature: Double
)

val records = ArrayList<Record>()
val map = HashMap<String, ArrayList<Record>>()

records.forEach { map.getOrPut("${it.year}-${it.month}") { ArrayList() }.add(it) }

C++

typedef struct record {
int year;
int month;
int day;
double temperature;
} Record;

std::vector<Record> records;
std::unordered_map<std::string, std::vector<Record>> map;

for (const auto &record : records) {
const std::string & key = std::to_string(record.year) + " " + std::to_string(record.month);
const auto & it = map.find(key);

if (it == map.end()) {
map.emplace_hint(it, key, std::vector<Record>())->second.push_back(record);
} else {
it->second.push_back(record);
}
}

//编辑

更广泛的 C++ 代码:https://pastebin.com/KqD02pSD

更广泛的 Kotlin 代码:https://pastebin.com/iG7hCqHT


重要修改

我已将 map 的键更改为 Int - [year * 100 + month]。结果仍然相似;慢 3 倍。

最佳答案

如果没有正确分析,总是很难说清楚为什么某段代码会以它的方式执行。特别是在谈论没有标准实现的 C++ 时,编译器和库实现的质量可能会因您使用的工具集而有很大差异(示例:12)。此外,标准要求 unordered_map 的接口(interface),不幸的是,严重限制了下面的实现可以做什么(查看 this talk 了解更多信息)。不幸的是,众所周知,std::unordered_map 不一定是人们所希望的最好的哈希表(some more on that)。

除了 std::unordered_map 本身的性能问题外,还有一些小的(很可能无关紧要的)问题可能会使您的 C++ 代码在这里处于额外的劣势。首先,您要构建 key 字符串,然后将其复制到 map 中。移动字符串可能会更有效。此外,std::to_string 可能比 Kotlin 字符串插值执行的转换成本更高,因为 std::to_string 被迫观察当前语言环境,而 Kotlin 字符串插值转换为一种固定的格式。在这里使用字符串作为键通常看起来很浪费,正如您的问题的评论中已经指出的那样。

我建议使用 map.try_emplace()而不是 map.emplace_hint()std::to_chars() 而不是 std::to_string()。除此之外,如果 Kotlin HashTable 只是一个通常比 std::unordered_map 更高效的容器,我不会感到惊讶,这可能是由于其接口(interface)设置的限制......

综上所述,我不确定您究竟想通过该基准测试达到什么目的。归根结底,您在这里所做的是比较两个随机选择的哈希表实现的性能。您永远无法选择一个而不是另一个,因为它们存在于两个完全独立的生态系统中,因此无论该基准测试的结果如何,它们似乎都不是非常……有用!?

关于c++ - C++ std::unordered_map 对比 Kotlin/Java HashMap 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com