From 23a8c007a668413c2e8cbd00984d223ed5ecfe05 Mon Sep 17 00:00:00 2001 From: Louis Wilson Date: Mon, 28 Oct 2019 17:20:14 -0700 Subject: [PATCH] Improve performance of string conversion 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). --- src/guid.cpp | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/guid.cpp b/src/guid.cpp index 3061a9b..bac10f9 100644 --- a/src/guid.cpp +++ b/src/guid.cpp @@ -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