Skip to content

Commit

Permalink
Improve performance of string conversion
Browse files Browse the repository at this point in the history
Convert to string with one call to snprintf and no string concatenations
instead of 5 calls to snprintf and 8 concatenations. Microbenchmarks
indicate that this is approximately 17% faster (1.17 times as fast).
  • Loading branch information
louiswins committed Oct 29, 2019
1 parent ca1bf4b commit 23a8c00
Showing 1 changed file with 8 additions and 19 deletions.
27 changes: 8 additions & 19 deletions src/guid.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,27 +113,16 @@ bool Guid::isValid() const
// convert to string using std::snprintf() and std::string
std::string Guid::str() const
{
char one[10], two[6], three[6], four[6], five[14];

snprintf(one, 10, "%02x%02x%02x%02x",
_bytes[0], _bytes[1], _bytes[2], _bytes[3]);
snprintf(two, 6, "%02x%02x",
_bytes[4], _bytes[5]);
snprintf(three, 6, "%02x%02x",
_bytes[6], _bytes[7]);
snprintf(four, 6, "%02x%02x",
_bytes[8], _bytes[9]);
snprintf(five, 14, "%02x%02x%02x%02x%02x%02x",
constexpr size_t guidSize = sizeof("01234567-0123-0123-0123-0123456789ab");
char out[guidSize];
snprintf(out, guidSize, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
_bytes[0], _bytes[1], _bytes[2], _bytes[3],
_bytes[4], _bytes[5],
_bytes[6], _bytes[7],
_bytes[8], _bytes[9],
_bytes[10], _bytes[11], _bytes[12], _bytes[13], _bytes[14], _bytes[15]);
const std::string sep("-");
std::string out(one);

out += sep + two;
out += sep + three;
out += sep + four;
out += sep + five;

return out;
return std::string(out, guidSize - 1);
}

// conversion operator for std::string
Expand Down

0 comments on commit 23a8c00

Please sign in to comment.