Skip to content

Commit 0859fbd

Browse files
authored
Merge pull request #2432 from analytically/iobufpool_putoptim
perf(iobufpool): optimize pool index calculations with O(1) bit manipulation
2 parents ea09cc0 + eba77a4 commit 0859fbd

1 file changed

Lines changed: 23 additions & 15 deletions

File tree

internal/iobufpool/iobufpool.go

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
// an allocation is purposely not documented. https://github.com/golang/go/issues/16323
55
package iobufpool
66

7-
import "sync"
7+
import (
8+
"math/bits"
9+
"sync"
10+
)
811

912
const minPoolExpOf2 = 8
1013

@@ -37,15 +40,14 @@ func Get(size int) *[]byte {
3740
}
3841

3942
func getPoolIdx(size int) int {
40-
size--
41-
size >>= minPoolExpOf2
42-
i := 0
43-
for size > 0 {
44-
size >>= 1
45-
i++
43+
if size < 2 {
44+
return 0
4645
}
47-
48-
return i
46+
idx := bits.Len(uint(size-1)) - minPoolExpOf2
47+
if idx < 0 {
48+
return 0
49+
}
50+
return idx
4951
}
5052

5153
// Put returns buf to the pool.
@@ -59,12 +61,18 @@ func Put(buf *[]byte) {
5961
}
6062

6163
func putPoolIdx(size int) int {
62-
minPoolSize := 1 << minPoolExpOf2
63-
for i := range pools {
64-
if size == minPoolSize<<i {
65-
return i
66-
}
64+
// Only exact power-of-2 sizes match pool buckets
65+
if size&(size-1) != 0 {
66+
return -1
67+
}
68+
69+
// Calculate log2(size) using trailing zeros count
70+
exp := bits.TrailingZeros(uint(size))
71+
idx := exp - minPoolExpOf2
72+
73+
if idx < 0 || idx >= len(pools) {
74+
return -1
6775
}
6876

69-
return -1
77+
return idx
7078
}

0 commit comments

Comments
 (0)