From 8c5df03e14d7c6e6d031cf02b6d5ddd2c4fe4f6d Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Thu, 9 Dec 2021 21:49:29 +1100 Subject: [PATCH] Minimize allocations due to heap escapes --- request-strategy/order.go | 2 +- request-strategy/piece-request-order.go | 21 ++++++++++++--------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/request-strategy/order.go b/request-strategy/order.go index f414226d..4068ed4d 100644 --- a/request-strategy/order.go +++ b/request-strategy/order.go @@ -81,7 +81,7 @@ func GetRequestablePieces(input Input, pro *PieceRequestOrder, f func(ih metainf } var allTorrentsUnverifiedBytes int64 pro.tree.Ascend(func(i btree.Item) bool { - _i := i.(pieceRequestOrderItem) + _i := i.(*pieceRequestOrderItem) ih := _i.key.InfoHash var t Torrent = input.Torrent(ih) var piece Piece = t.Piece(_i.key.Index) diff --git a/request-strategy/piece-request-order.go b/request-strategy/piece-request-order.go index e0af7487..0b1d6b4e 100644 --- a/request-strategy/piece-request-order.go +++ b/request-strategy/piece-request-order.go @@ -35,8 +35,8 @@ type pieceRequestOrderItem struct { state PieceRequestOrderState } -func (me pieceRequestOrderItem) Less(other btree.Item) bool { - otherConcrete := other.(pieceRequestOrderItem) +func (me *pieceRequestOrderItem) Less(other btree.Item) bool { + otherConcrete := other.(*pieceRequestOrderItem) return pieceOrderLess( pieceOrderInput{ PieceRequestOrderState: me.state, @@ -53,7 +53,7 @@ func (me *PieceRequestOrder) Add(key PieceRequestOrderKey, state PieceRequestOrd if _, ok := me.keys[key]; ok { panic(key) } - if me.tree.ReplaceOrInsert(pieceRequestOrderItem{ + if me.tree.ReplaceOrInsert(&pieceRequestOrderItem{ key: key, state: state, }) != nil { @@ -63,13 +63,15 @@ func (me *PieceRequestOrder) Add(key PieceRequestOrderKey, state PieceRequestOrd } func (me *PieceRequestOrder) Update(key PieceRequestOrderKey, state PieceRequestOrderState) { - if me.tree.Delete(me.existingItemForKey(key)) == nil { + item := me.existingItemForKey(key) + if item.state == state { + return + } + if me.tree.Delete(&item) == nil { panic(fmt.Sprintf("%#v", key)) } - if me.tree.ReplaceOrInsert(pieceRequestOrderItem{ - key: key, - state: state, - }) != nil { + item.state = state + if me.tree.ReplaceOrInsert(&item) != nil { panic(key) } me.keys[key] = state @@ -83,7 +85,8 @@ func (me *PieceRequestOrder) existingItemForKey(key PieceRequestOrderKey) pieceR } func (me *PieceRequestOrder) Delete(key PieceRequestOrderKey) { - if me.tree.Delete(me.existingItemForKey(key)) == nil { + item := me.existingItemForKey(key) + if me.tree.Delete(&item) == nil { panic(key) } delete(me.keys, key)