Skip to content

Commit 74bf850

Browse files
committed
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.
1 parent 489030f commit 74bf850

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/util/strencodings.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -579,13 +579,14 @@ std::string Capitalize(std::string str)
579579

580580
std::string HexStr(const Span<const uint8_t> s)
581581
{
582-
std::string rv;
582+
std::string rv(s.size() * 2, '\0');
583583
static constexpr char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
584584
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
585-
rv.reserve(s.size() * 2);
586-
for (uint8_t v: s) {
587-
rv.push_back(hexmap[v >> 4]);
588-
rv.push_back(hexmap[v & 15]);
585+
auto it = rv.begin();
586+
for (uint8_t v : s) {
587+
*it++ = hexmap[v >> 4];
588+
*it++ = hexmap[v & 15];
589589
}
590+
assert(it == rv.end());
590591
return rv;
591592
}

0 commit comments

Comments
 (0)