From d5ece3c4b5e109f65f5d3315c43239dd87bb2c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C5=91rinc?= Date: Sat, 9 Mar 2024 13:31:40 +0100 Subject: [PATCH 1/2] Reserve hrp memory in Decode and LocateErrors --- src/bech32.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/bech32.cpp b/src/bech32.cpp index c3c4ca8006fb4..fafd2007a6875 100644 --- a/src/bech32.cpp +++ b/src/bech32.cpp @@ -393,6 +393,7 @@ DecodeResult Decode(const std::string& str, CharLimit limit) { values[i] = rev; } std::string hrp; + hrp.reserve(pos); for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } @@ -425,6 +426,7 @@ std::pair> LocateErrors(const std::string& str, Ch } std::string hrp; + hrp.reserve(pos); for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } From 07f64177a49f1b6b4d486d10cf67fddfa3c995eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C5=91rinc?= Date: Sat, 9 Mar 2024 14:08:00 +0100 Subject: [PATCH 2/2] Reduce memory copying operations in bech32 encode Here I've reduced the memory reallocations and copying operations in bech32 encode, making it ~15% faster. make && ./src/bench/bench_bitcoin --filter='Bech32Encode' --min-time=1000 Before: | ns/byte | byte/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 19.97 | 50,074,562.72 | 0.1% | 1.06 | `Bech32Encode` After: | ns/byte | byte/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 17.33 | 57,687,668.20 | 0.1% | 1.10 | `Bech32Encode` Co-authored-by: josibake --- src/bech32.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/bech32.cpp b/src/bech32.cpp index fafd2007a6875..d8d31a415c220 100644 --- a/src/bech32.cpp +++ b/src/bech32.cpp @@ -363,13 +363,13 @@ std::string Encode(Encoding encoding, const std::string& hrp, const data& values // to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the // result will always be invalid. for (const char& c : hrp) assert(c < 'A' || c > 'Z'); - data checksum = CreateChecksum(encoding, hrp, values); - data combined = Cat(values, checksum); - std::string ret = hrp + '1'; - ret.reserve(ret.size() + combined.size()); - for (const auto c : combined) { - ret += CHARSET[c]; - } + + std::string ret; + ret.reserve(hrp.size() + 1 + values.size() + CHECKSUM_SIZE); + ret += hrp; + ret += '1'; + for (const uint8_t& i : values) ret += CHARSET[i]; + for (const uint8_t& i : CreateChecksum(encoding, hrp, values)) ret += CHARSET[i]; return ret; }