From 50958bac5ce2d5c9351188a27c29b083c409f9d0 Mon Sep 17 00:00:00 2001 From: maskpp Date: Sun, 27 Jul 2025 14:30:38 +0800 Subject: [PATCH] reuse the cache if it is not null --- core/txpool/legacypool/list.go | 37 +++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/core/txpool/legacypool/list.go b/core/txpool/legacypool/list.go index 736c28ec4a..c72323cc62 100644 --- a/core/txpool/legacypool/list.go +++ b/core/txpool/legacypool/list.go @@ -78,11 +78,19 @@ func (m *SortedMap) Get(nonce uint64) *types.Transaction { // index. If a transaction already exists with the same nonce, it's overwritten. func (m *SortedMap) Put(tx *types.Transaction) { nonce := tx.Nonce() - if m.items[nonce] == nil { - heap.Push(m.index, nonce) + // If the tx already exit, return immediately. + if m.items[nonce] != nil { + return } + + m.items[nonce] = tx + heap.Push(m.index, nonce) + m.cacheMu.Lock() - m.items[nonce], m.cache = tx, nil + if m.cache != nil { + m.cache = append(m.cache, tx) + sort.Sort(types.TxByNonce(m.cache)) + } m.cacheMu.Unlock() } @@ -162,9 +170,9 @@ func (m *SortedMap) Cap(threshold int) types.Transactions { // Otherwise gather and drop the highest nonce'd transactions var drops types.Transactions 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]) + for _, nonce := range (*m.index)[threshold:] { + drops = append(drops, m.items[nonce]) + delete(m.items, nonce) } *m.index = (*m.index)[:threshold] // The sorted m.index slice is still a valid heap, so there is no need to @@ -173,7 +181,7 @@ func (m *SortedMap) Cap(threshold int) types.Transactions { // If we had a cache, shift the back m.cacheMu.Lock() if m.cache != nil { - m.cache = m.cache[:len(m.cache)-len(drops)] + m.cache = m.cache[:threshold] } m.cacheMu.Unlock() return drops @@ -188,15 +196,16 @@ func (m *SortedMap) Remove(nonce uint64) bool { return false } // Otherwise delete the transaction and fix the heap index - for i := 0; i < m.index.Len(); i++ { - if (*m.index)[i] == nonce { - heap.Remove(m.index, i) - break - } - } + index := slices.Index(*m.index, nonce) + heap.Remove(m.index, index) delete(m.items, nonce) + m.cacheMu.Lock() - m.cache = nil + if m.cache != nil { + slices.DeleteFunc(m.cache, func(tx *types.Transaction) bool { + return tx.Nonce() == nonce + }) + } m.cacheMu.Unlock() return true