How can I increase the performance in a map lookup with key type std::string?

后端 未结 14 978
天涯浪人
天涯浪人 2021-02-05 23:25

I\'m using a std::map (VC++ implementation) and it\'s a little slow for lookups via the map\'s find method.

The key type is std::string.

14条回答
  •  野的像风
    2021-02-05 23:41

    Here are some things you can consider:

    0) Are you sure this is where the performance bottleneck is? Like the results from Quantify, Cachegrind, gprof or something like that? Because lookups on such a smap map should be fairly fast...

    1) You can override the functor used to compare the keys in std::map<>, there is a second template parameter to do that. I doubt you can do much better than operator<, however.

    2) Are the contents of the map changing a lot? If not, and given the very small size of your map, maybe using a sorted vector and binary search could yield better results (for example because you can exploit memory locality better.

    3) Are the elements known at compile time? You could use a perfect hash function to improve lookup times if that is the case. Search for gperf on the web.

    4) Do you have a lot of lookups that fail to find anything? If so, maybe comparing with the first and last elements in the collection may eliminate many mismatches quicker than a full search every time.

    These have been suggested already, but in more detail:

    5) Since you have so few strings, maybe you could use a different key. For example, are your keys all the same size? Can you use a class containing a fixed-length array of characters? Can you convert your strings to numbers or some data structure with only numbers?

提交回复
热议问题