From 0c5a89c2d444639d4c9a02e3d727159fb68aa8e3 Mon Sep 17 00:00:00 2001 From: Calvin Kim Date: Fri, 5 May 2023 22:19:54 +0900 Subject: [PATCH] blockchain: Add benchmark for using a map vs a slice Benchmark added to compare the performance of a map vs a slice when fetching utxos. The benchmark shows roughly 25% performance improvement when using slices instead of a map. --- blockchain/bench_test.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/blockchain/bench_test.go b/blockchain/bench_test.go index eee4340bc89..9ecc8342416 100644 --- a/blockchain/bench_test.go +++ b/blockchain/bench_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/wire" ) // BenchmarkIsCoinBase performs a simple benchmark against the IsCoinBase @@ -29,3 +30,33 @@ func BenchmarkIsCoinBaseTx(b *testing.B) { IsCoinBaseTx(tx) } } + +func BenchmarkUtxoFetchMap(b *testing.B) { + block := Block100000 + transactions := block.Transactions + b.ResetTimer() + + for i := 0; i < b.N; i++ { + needed := make(map[wire.OutPoint]struct{}, len(transactions)) + for _, tx := range transactions[1:] { + for _, txIn := range tx.TxIn { + needed[txIn.PreviousOutPoint] = struct{}{} + } + } + } +} + +func BenchmarkUtxoFetchSlices(b *testing.B) { + block := Block100000 + transactions := block.Transactions + b.ResetTimer() + + for i := 0; i < b.N; i++ { + needed := make([]wire.OutPoint, 0, len(transactions)) + for _, tx := range transactions[1:] { + for _, txIn := range tx.TxIn { + needed = append(needed, txIn.PreviousOutPoint) + } + } + } +}