title: How could I speed up comparison of std::string against string literals?
body: <p>I have a bunch of code where objects of type <code>std::string</code> are compared for equality against string literals. Something like this:</p>
  
  <pre><code>//const std:string someString = //blahblahblah;
  if( someString == "(" ) {
     //do something
  } else if( someString == ")" ) {
     //do something else
  } else if// this chain can be very long
  </code></pre>
  
  <p>The comparison time accumulates to a serious amount (yes, I profiled) and so it'd be nice to speed it up.</p>
  
  <p>The code compares the string against numerous short string literals and this comparison can hardly be avoided. Leaving the string declared as <code>std::string</code> is most likely inevitable  - there're thousands lines of code like that. Leaving string literals and comparison with <code>==</code> is also likely inevitable - rewriting the whole code would be a pain.</p>
  
  <p>The problem is the STL implementation that comes with Visual C++11 uses somewhat strange approach. <code>==</code> is mapped onto <code>std::operator==(const basic_string&amp;, const char*)</code> which calls <code>basic_string::compare( const char* )</code> which in turn calls <code>std::char_traits&lt;char&gt;( const char* )</code> which calls <code>strlen()</code> to compute the length of the string literal. Then the comparison runs for the two strings and lengths of both strings are passed into that comparison.</p>
  
  <p>The compiler has a hard time analyzing all this and emits code that traverses the string literal twice. With short literals that's not much time but every comparison involves traversing the literal twice instead of once. Simply calling <code>strcmp()</code> would most likely be faster.</p>
  
  <p>Is there anything I could do like perhaps writing a custom comparator class that would help avoid traversing the string literals twice in this scenario?</p>