Fastest quote-escaping implementation?

c++, escaping, replace, string

Solution

If speed is a concern you should use a hand-written function to do this. Notice the use of `reserve()` to try to keep memory (re)allocation to a minimum.

string escape_quotes(const string &before)
{
    string after;
    after.reserve(before.length() + 4);

    for (string::size_type i = 0; i < before.length(); ++i) {
        switch (before[i]) {
            case '"':
            case '\\':
                after += '\\';
                // Fall through.

            default:
                after += before[i];
        }
    }

    return after;
}

Problem

I'm working on some code that is normalizing a lot of data. At the end of processing, a number of key="value" pairs is written out to a file. The "value" part could be anything, so at the point of output the values must have any embedded quotes escaped as \". Right now, I'm using the following: ``` outstream << boost::regex_replace(src, rxquotesearch, quoterepl); // (where rxquotesearch is boost::regex("\"") and quoterepl is "\\\\\"") ``` However, gprof shows I'm spending most of my execution time in this method, since I have to call it for every value for every line. I'm curious if there is a faster way than this. I can't use std::replace since I'm replacing one character with two. Thanks for any advice.

Original source