From 74bf850ac47735f2ef4306059d3e664d40cac85e Mon Sep 17 00:00:00 2001 From: Martin Ankerl Date: Sun, 14 Feb 2021 12:10:15 +0100 Subject: faster HexStr => 13% faster blockToJSON `std::string`'s push_back is rather slow because it needs to check & update the string size. For `HexStr` the output string size is already easily know, so we can initially create the string with the correct size and then just assign the data. `HexStr` is heavily usd in `blockToJSON`, so this change is a noticeable benefit. Benchmark on an i7-8700 @3.2GHz: * 71,315,461.00 ns/op master * 62,842,490.00 ns/op this commit So this little change makes `blockToJSON` about ~13% faster. --- src/util/strencodings.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src/util') diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index f3d54a2ac9..deabc05de4 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -579,13 +579,14 @@ std::string Capitalize(std::string str) std::string HexStr(const Span s) { - std::string rv; + std::string rv(s.size() * 2, '\0'); static constexpr char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - rv.reserve(s.size() * 2); - for (uint8_t v: s) { - rv.push_back(hexmap[v >> 4]); - rv.push_back(hexmap[v & 15]); + auto it = rv.begin(); + for (uint8_t v : s) { + *it++ = hexmap[v >> 4]; + *it++ = hexmap[v & 15]; } + assert(it == rv.end()); return rv; } -- cgit v1.2.3