From a193bb0c730e413db56424a084cc172892c68dd5 Mon Sep 17 00:00:00 2001 From: colin <102356659+colinlyguo@users.noreply.github.com> Date: Fri, 16 Feb 2024 02:50:17 +0800 Subject: [PATCH] core/txpool/legacypool: remove a redundant heap.Init (#28910) Co-authored-by: Martin HS Co-authored-by: Felix Lange --- core/txpool/legacypool/list.go | 7 ++++--- core/txpool/legacypool/list_test.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/core/txpool/legacypool/list.go b/core/txpool/legacypool/list.go index a28e09f99..f0f9f213f 100644 --- a/core/txpool/legacypool/list.go +++ b/core/txpool/legacypool/list.go @@ -28,6 +28,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/holiman/uint256" + "golang.org/x/exp/slices" ) // nonceHeap is a heap.Interface implementation over 64bit unsigned integers for @@ -160,14 +161,14 @@ func (m *sortedMap) Cap(threshold int) types.Transactions { } // Otherwise gather and drop the highest nonce'd transactions var drops types.Transactions - - sort.Sort(*m.index) + slices.Sort(*m.index) for size := len(m.items); size > threshold; size-- { drops = append(drops, m.items[(*m.index)[size-1]]) delete(m.items, (*m.index)[size-1]) } *m.index = (*m.index)[:threshold] - heap.Init(m.index) + // The sorted m.index slice is still a valid heap, so there is no need to + // reheap after deleting tail items. // If we had a cache, shift the back m.cacheMu.Lock() diff --git a/core/txpool/legacypool/list_test.go b/core/txpool/legacypool/list_test.go index 67256f63b..8587c66f7 100644 --- a/core/txpool/legacypool/list_test.go +++ b/core/txpool/legacypool/list_test.go @@ -87,3 +87,25 @@ func BenchmarkListAdd(b *testing.B) { } } } + +func BenchmarkListCapOneTx(b *testing.B) { + // Generate a list of transactions to insert + key, _ := crypto.GenerateKey() + + txs := make(types.Transactions, 32) + for i := 0; i < len(txs); i++ { + txs[i] = transaction(uint64(i), 0, key) + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + list := newList(true) + // Insert the transactions in a random order + for _, v := range rand.Perm(len(txs)) { + list.Add(txs[v], DefaultConfig.PriceBump) + } + b.StartTimer() + list.Cap(list.Len() - 1) + b.StopTimer() + } +}