Fastest way to capitalize words

boost, c++, stdstring

Solution

Had this exact question when dealing with DNA sequences where the input is not guaranteed to be upper case, and where `boost::to_upper` was a bottle-neck in the code. Changing to this:

template<typename T_it>
void SequenceToUpperCase( T_it begin, T_it end )
{
    // Convert to upper: clear the '32' bit, 0x20 in hex. And with the
    // inverted bit string (~).
    for ( auto it = begin; it != end; ++it )
        *it &= ~0x20;
}

resulted in a huge speed increase. I'm sure it is possible to further optimize by e.g. flipping 8 bytes at once but with the above code the upper-case is near-instantaneous for us. For lower-case: do:

        *it |= 0x20;

Problem

What is the fastest way to capitalize words (std::string) using C++? On Debian Linux using g++ 4.6.3 with the -O3 flag, this function using `boost::to_lower` will capitalize 81,450,625 words in roughly 24 seconds in a single thread of execution on a AMD Phenom(tm) II X6 1090T Processor (3200 MHz). ``` void Capitalize( std::string& word ) { boost::to_lower( word ); word[0] = toupper( word[0] ); } ``` This function using `std::transform` does the same thing in roughly 10 seconds. I clear the VM between testing, so I don't think this difference is a fluke: `sync && echo 3 > /proc/sys/vm/drop_caches` ``` void Capitalize( std::string& word ) { std::transform(word.begin(), word.end(), word.begin(), ::tolower); word[0] = toupper( word[0] ); } ``` Are there faster ways? I would not want to lose portability for the sake of speed, but if there are faster ways to do this that work in std C++ or std C++ with boost, I'd like to try them. Thanks.

Original source