I have created Andorid project to measure some equivalent pices of code and this one had me stuck on why? Why is C++ 3x slower here?
I already made some tweaks to C++ as immediate try to emplace and then push_back was slower than current approach, but still. Complexities here should be same, right?
Kotlin: 139,945,691 ns (139 ms)
C++: 347,100,764 ns (347 ms)
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);
}
}
// Edit
Broader C++ code: https://pastebin.com/KqD02pSD
Broader Kotlin code: https://pastebin.com/iG7hCqHT
Important Edit
I have changed key of maps to Int
- [year * 100 + month]
. And results are still similar; 3x slower.