From: Matt Joiner <anacrolix@gmail.com>
Date: Sat, 8 May 2021 00:35:23 +0000 (+1000)
Subject: Reduce allocations in iterBitmapsDistinct
X-Git-Tag: v1.28.0~18^2
X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=95d72a452a8fb258d641e5e9958234920138620e;p=btrtrc.git

Reduce allocations in iterBitmapsDistinct
---

diff --git a/misc_test.go b/misc_test.go
index 419ec4d0..f3a37683 100644
--- a/misc_test.go
+++ b/misc_test.go
@@ -23,14 +23,20 @@ func TestTorrentOffsetRequest(t *testing.T) {
 	check(13, 5, 13, Request{}, false)
 }
 
-func TestIterBitmapsDistinct(t *testing.T) {
-	var skip, first, second bitmap.Bitmap
-	skip.Add(1)
-	first.Add(1, 0, 3)
-	second.Add(1, 2, 0)
-	skipCopy := skip.Copy()
-	assert.Equal(t, []interface{}{0, 3, 2}, iter.ToSlice(iterBitmapsDistinct(&skipCopy, first, second)))
-	assert.Equal(t, []int{1}, skip.ToSortedSlice())
+func BenchmarkIterBitmapsDistinct(t *testing.B) {
+	t.ReportAllocs()
+	for range iter.N(t.N) {
+		var skip, first, second bitmap.Bitmap
+		skip.Add(1)
+		first.Add(1, 0, 3)
+		second.Add(1, 2, 0)
+		skipCopy := skip.Copy()
+		t.StartTimer()
+		output := iter.ToSlice(iterBitmapsDistinct(&skipCopy, first, second))
+		t.StopTimer()
+		assert.Equal(t, []interface{}{0, 3, 2}, output)
+		assert.Equal(t, []int{1}, skip.ToSortedSlice())
+	}
 }
 
 func TestSpewConnStats(t *testing.T) {
diff --git a/peerconn.go b/peerconn.go
index de82cf3b..0c276808 100644
--- a/peerconn.go
+++ b/peerconn.go
@@ -743,12 +743,13 @@ func (cn *PeerConn) updateRequests() {
 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
 	return func(cb iter.Callback) {
 		for _, bm := range bms {
+			bm.Sub(*skip)
 			if !iter.All(
 				func(i interface{}) bool {
 					skip.Add(i.(int))
 					return cb(i)
 				},
-				bitmap.Sub(bm, *skip).Iter,
+				bm.Iter,
 			) {
 				return
 			}