Christian Christmann wrote:
> Hi,
>
> I've profiled one of my C++ projects and figured out that the
> program spends a lot of time with STL map's function "find".
>
> One of my classes possesses an STL map of the structure
>
> map< string, string > myMap;
>
> The function that consumes a substantial fraction of the
> program execution, searches in the map:
>
>
> string findString( const char *lab )
> {
> string tmp( lab );
>
> map< string, string >::const_iterator it = myMap.find( tmp.c_str() );
map< string, string >::const_iterator it = myMap.find( tmp );
>
> if ( it != myMap.end() ) {
> string myString( it->second.c_str() );
> return myString;
return it->second;
> }
>
> // Otherwise
> string myString( lab );
Why again?
return tmp;
>
> return myString;
> }
>
>
> Do you see any possibility to optimize the "find" function on "myMap"?
You could try a different comparison predicate: if many of your string have
a common prefix, lexicographic comparison may look at many characters
before being able to decide. In this case, short-lex order could take
advantage of strings being of different lengths.
Also, if your map is more or less static, i.e., built once and used
afterward for searching only, you could use
std::vector< std:

air< std::string, std::string > >
instead: put all pairs in there, sort, and do table lookup by binary search.
However, that should not make a big difference.
Another option is to use an unordered_map instead where you can play around
with a hash function.
> And in general, do you have any suggestions how to improve the function
> "findString"?
See above: I wondered why you are going through c_str(). Your map knows
strings, just use them.
Best
Kai-Uwe Bux