Post · 1 min read· p. 64

STL: map with string as key — access speedup

The idea is quite simple: we do not have a single stl::map<string, something>, but a vector of maps, indexed with O(1) time — each map stores keys sharing certain properties. Drawback: additional memory.

I've tested following grouping schemes:

  1. the length of string,
  2. the first letter of string (one level trie),
  3. both length and the first letter.

Third is the fastest — around 60% faster then plain std::map from GCC (red-black tree).

Tests: my program read plain text (I've used The Illiad from http://gutenberg.org), text is split into words (190000) and then each words is inserted into a dictionary (28000 distinct words); then the same words are searched in dictionaries. Table below summarizes results on my computer (gcc 4.3.4 from Cygwin).

data structrunning time [ms]speedup [%]
minavgmaxminavgmax
inserting
std::map269287355100100100
first char2182413958184111
length218240345818497
len./char165172207616058
searching
std::map295322483100100100
first char243263460828295
length238248292807760
len./char184190241626050

Download test program.