Skip to content

Instantly share code, notes, and snippets.

@AshKash
Last active June 16, 2019 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshKash/ebf1f70949e76439d6ffed9ccde337be to your computer and use it in GitHub Desktop.
Save AshKash/ebf1f70949e76439d6ffed9ccde337be to your computer and use it in GitHub Desktop.
C++ unordered_maps vs Go map benchmark
#include <unordered_map>
#include <string>
#include <vector>
const int numOfStrings = 100000;
const int numOfIterations = 1000;
// adapted from: https://medium.com/@griffinish/c-and-golang-neck-and-neck-on-maps-e7867adfadc6
// g++ -std=c++0x -O3 -o maps_cxx maps.cpp
//
// time ./maps_cxx
//
// real 0m18.676s
// user 0m16.818s
// sys 0m1.858s
//
// g++ (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4
int main() {
// First make list of numeric strings
// This should be one relatively cheap
// loop. The container holds string
// representations of integers.
std::vector<std::string> numStrings;
numStrings.reserve(numOfStrings);
for (auto i=0; i<numOfStrings; i++) {
numStrings.push_back(std::to_string(i)) ;
}
// Check insert speed, 10 million inserts in total
for (auto i=0; i<numOfIterations; i++){
std::unordered_map<std::string,int> strToInt;
strToInt.reserve(numOfStrings);
for (auto& item : numStrings){
strToInt[item] = item.size();
}
}
return 0;
}
package main
// adapted from: https://medium.com/@griffinish/c-and-golang-neck-and-neck-on-maps-e7867adfadc6
// go build maps.go
//
// time ./maps
//
// real 0m7.775s
// user 0m9.900s
// sys 0m0.088s
//
// go version go1.12 linux/amd64
import "fmt"
const numOfStrings = 100000
const numOfIterations = 1000
func main() {
// First make list of numeric strings
// This should be one relatively cheap
// loop. The container holds string
// representations of numbers.
numStrings := make([]string, 0, numOfStrings)
for i := 0; i < numOfStrings; i++ {
numStrings = append(numStrings, fmt.Sprint(i))
}
for i := 0; i < numOfIterations; i++ {
strToInt := make(map[string]int, numOfStrings)
for _, item := range numStrings {
strToInt[item] = len(item)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment