Converting integers to strings I drafted a method that I intend to use to convert integers to strings. Is there a way to make it faster? Are there any "simple" changes I could make to improve its performance? This cannot be done with C++11.

std::string to_string(int val) {
    static std::string str;
    static std::stringstream ss;
    ss &lt;&lt; val;
    ss &gt;&gt; str;
    ss.clear();
    return str;
}
I have a big concern with this code. It uses local static variables, so this will result in race conditions if used in a multithreaded program.

I assume you did that to improve performance? Constructing the std::stringstream could potentially incur some overhead. So having that variable as a static would be understandable if you are sure no race conditions apply. But the str string certainly doesn't have to be a local static. Actually, it is not needed at all, since stringstream::str() exists.

I think you have two options here:

Make it thread-safe and cleaner at the cost of some extra object construction every call, which is probably not a big deal:

std::string to_string(int val) {
    std::stringstream ss;
    ss &lt;&lt; val;
    return ss.str();
}


Or, if you need ultimate performance and cannot afford the chance of a memory allocation by std::stringstream, then you could use sprintf, snprintf or itoa. This is a possible implementation, also thread safe, with no statics:

std::string to_string(int val) {
    // Buffer size is arbitrary in this example. Could be smaller.
    // 128 is more than enough for any integer number.
    char buffer[128];
    std::snprintf(buffer, sizeof(buffer), "%i", val);
    return buffer;
}


I suggest going with the first one, but if you have a justifiable performance concern, then the second one should perform slightly better.