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

后端 未结 14 1006
天涯浪人
天涯浪人 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:43

    You might consider pre-computing a hash for a string, and saving that in your map. Doing so gives the advantage of hash compares instead of string compares during the search through the std::map tree.

    class HashedString
    {
      unsigned m_hash;
      std::string m_string;
    
    public:
      HashedString(const std::string& str)
        : m_hash(HashString(str))
        , m_string(str)
      {};
      // ... copy constructor and etc...
    
      unsigned GetHash() const {return m_hash;}
      const std::string& GetString() const {return m_string;}
    };
    

    This has the benefits of computing a hash of the string once, on construction. After this, you could implement a comparison function:

    struct comp
    {
      bool operator()(const HashedString& lhs, const HashedString& rhs)
      {
        if(lhs.GetHash() < rhs.GetHash()) return true;
        if(lhs.GetHash() > rhs.GetHash()) return false;
        return lhs.GetString() < rhs.GetString();
      }
    };
    

    Since hashes are now computed on HashedString construction, they are stored that way in the std::map, and so the compare can happen very quickly (an integer compare) in an astronomically high percentage of the time, falling back on standard string compares when the hashes are equal.

提交回复
热议问题