Skip to content

Commit 1ed859e

Browse files
committed
Merge bitcoin/bitcoin#21173: util: faster HexStr => 13% faster blockToJSON
74bf850 faster HexStr => 13% faster blockToJSON (Martin Ankerl) Pull request description: `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. ACKs for top commit: laanwj: Code review ACK 74bf850 theStack: re-ACK 74bf850 Tree-SHA512: fc99105123edc11f4e40ed77aea80cf7f32e49c53369aa364b38395dcb48575e15040b0489ed30d0fe857c032a04e225c33e9d95cdfa109a3cb5a6ec9a972415
2 parents 2fc111b + 74bf850 commit 1ed859e

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
@@ -593,13 +593,14 @@ std::string Capitalize(std::string str)
593593

594594
std::string HexStr(const Span<const uint8_t> s)
595595
{
596-
std::string rv;
596+
std::string rv(s.size() * 2, '\0');
597597
static constexpr char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
598598
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
599-
rv.reserve(s.size() * 2);
600-
for (uint8_t v: s) {
601-
rv.push_back(hexmap[v >> 4]);
602-
rv.push_back(hexmap[v & 15]);
599+
auto it = rv.begin();
600+
for (uint8_t v : s) {
601+
*it++ = hexmap[v >> 4];
602+
*it++ = hexmap[v & 15];
603603
}
604+
assert(it == rv.end());
604605
return rv;
605606
}

0 commit comments

Comments
 (0)