From ea62aaed3b1851605c9ff33a9d9f9edcb53828a5 Mon Sep 17 00:00:00 2001 From: ismaelsadeeq Date: Mon, 28 Oct 2024 13:03:11 +0100 Subject: [PATCH] rpc: reserve space for `UniValue` variables in `blockToJSON` - Reserving space avoid reallocation, this provide noticeable performance increase in verbosity 1. --- src/core_write.cpp | 3 +++ src/rpc/blockchain.cpp | 1 + 2 files changed, 4 insertions(+) diff --git a/src/core_write.cpp b/src/core_write.cpp index 253dfde100..14836f5148 100644 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -181,6 +181,7 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin{UniValue::VARR}; + vin.reserve(tx.vin.size()); // If available, use Undo data to calculate the fee. Note that txundo == nullptr // for coinbase transactions and for transactions where undo data is unavailable. @@ -203,6 +204,7 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry } if (!tx.vin[i].scriptWitness.IsNull()) { UniValue txinwitness(UniValue::VARR); + txinwitness.reserve(tx.vin[i].scriptWitness.stack.size()); for (const auto& item : tx.vin[i].scriptWitness.stack) { txinwitness.push_back(HexStr(item)); } @@ -232,6 +234,7 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry entry.pushKV("vin", std::move(vin)); UniValue vout(UniValue::VARR); + vout.reserve(tx.vout.size()); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 89e01bbf7f..dfb82ee0fd 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -183,6 +183,7 @@ UniValue blockToJSON(BlockManager& blockman, const CBlock& block, const CBlockIn result.pushKV("size", (int)::GetSerializeSize(TX_WITH_WITNESS(block))); result.pushKV("weight", (int)::GetBlockWeight(block)); UniValue txs(UniValue::VARR); + txs.reserve(block.vtx.size()); switch (verbosity) { case TxVerbosity::SHOW_TXID: