I was using an map with a map<long, X> For tuning performance I decided to experiment with unordered map too. I tried a 100k inserts using the operator[] with both. The map took ~140seconds whereas the unordered map tool ~230 seconds for the same code. I was expecting the unordered_map to be much faster! Am I wrong or is something fishy here?
Have searched for previous answers but they all point to unordered_map being faster. Hence the question. Can provide more details. Ran the below benchmark, first case takes ~0 seconds, 2nd one takes 8 seconds.
#include <map> #include <unordered_map> #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; struct X{ long a, b, c, d, e, f; string x, y, z; }; struct mapZ{ long id; map<long, X> xMap; }; struct unmapZ{ long id; unordered_map<long, X> xUnMap; }; unmapZ & addUnMap(unmapZ & um, X & xtmp) { um.xUnMap[xtmp.a] = xtmp; return(um); } mapZ & addMap(mapZ & mp, X & xtmp) { mp.xMap[xtmp.a] = xtmp; return(mp); } int main() { int numItr = 10000; map<long, X> myMap; unordered_map<long, X> myUnMap; mapZ mp; unmapZ uz; uz.id = (long)1; uz.xUnMap = myUnMap; mp.id = (long)1; mp.xMap = myMap; time_t start = time(0); for(int i = 0; i < numItr; i++) { long id = (long)rand(); X tmp; tmp.a = id; tmp.b = id; tmp.c = id; tmp.d = id; tmp.e=id; tmp.f=id; tmp.x = "ABCDEF"; tmp.y = "WXYZS"; tmp.z = "UVGHJ"; mp = addMap(mp, tmp); } cout << "size of map: " << mp.xMap.size() << "\n"; time_t eof_map = time(0); for(int i = 0; i < numItr; i++) { long id = (long)rand(); X tmp; tmp.a = id; tmp.b = id; tmp.c = id; tmp.d = id; tmp.e=id; tmp.f=id; tmp.x = "ABCDEF"; tmp.y = "WXYZS"; tmp.z = "UVGHJ"; uz = addUnMap(uz, tmp); } cout << "size of unmap: " << uz.xUnMap.size() << "\n"; time_t eof_unmap = time(0); cout << "Map inset time: " << eof_map - start << "\n"; cout << "Unord Map insert time: " << eof_unmap - eof_map << "\n"; return(0); } Here is the command line to run the benchmark:
g++ -O3 -std=c++0x -m64 -Wno-write-strings -fopenmp mapTest.cpp running GCC 4.6 on Ubuntu.