Code to efficiently convert an 8-bit integer to a std::string, or it would be, if retval.resize didn't take so long:
static std::string cvt(char val)
{
std::string retval(5, '\0');
int i = 0;
char ch = 0;
if (val < 0) {
retval[i] = '-';
++i;
if (val <= -100) {
ch = '1';
val += 100;
}
val = -val;
}
else if (val >= 100) {
ch |= '1';
val -= 100;
}
if (ch) {
retval[i] = ch;
++i;
ch = '0';
}
if (val >= 80) {
ch |= '8';
val -= 80;
}
else if (val >= 40) {
ch |= '4';
val -= 40;
}
if (val >= 20) {
ch |= '2';
val -= 20;
}
if (val >= 10) {
ch |= '1';
val -= 10;
}
if (ch) {
retval[i] = ch;
++i;
}
retval[i] = '0' + val;
retval.resize(i+1);
return retval;
}
40% of time spent in std::string::resize is spent inside a useless call to memmove with length == 0
More time is spent calculating the parameters to memmove. It appears that parameter setup and the actual call to memmove together account for >90% of the time in std::string::resize.
std::string::resize should not call memmove when the size is being reduced, it should just adjust the internal size field.