2020-08-13 20:12:22 +00:00
|
|
|
package leveledbytebufferpool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/bits"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
// pools contains pools for byte slices of various capacities.
|
|
|
|
//
|
2024-06-13 14:56:23 +00:00
|
|
|
// pools[0] is for capacities from 0 to 64
|
|
|
|
// pools[1] is for capacities from 65 to 128
|
|
|
|
// pools[2] is for capacities from 129 to 256
|
2022-07-11 16:21:59 +00:00
|
|
|
// ...
|
2024-06-13 14:56:23 +00:00
|
|
|
// pools[n] is for capacities from 2^(n+5)+1 to 2^(n+6)
|
2020-08-13 20:12:22 +00:00
|
|
|
//
|
2021-03-14 20:56:23 +00:00
|
|
|
// Limit the maximum capacity to 2^18, since there are no performance benefits
|
|
|
|
// in caching byte slices with bigger capacities.
|
2024-06-13 14:56:23 +00:00
|
|
|
var pools [12]sync.Pool
|
2020-08-13 20:12:22 +00:00
|
|
|
|
|
|
|
// Get returns byte buffer with the given capacity.
|
|
|
|
func Get(capacity int) *bytesutil.ByteBuffer {
|
2020-08-28 06:44:08 +00:00
|
|
|
id, capacityNeeded := getPoolIDAndCapacity(capacity)
|
2020-08-13 20:12:22 +00:00
|
|
|
for i := 0; i < 2; i++ {
|
2020-08-16 19:12:19 +00:00
|
|
|
if id < 0 || id >= len(pools) {
|
2020-08-13 20:12:22 +00:00
|
|
|
break
|
|
|
|
}
|
2020-08-16 19:12:19 +00:00
|
|
|
if v := pools[id].Get(); v != nil {
|
|
|
|
return v.(*bytesutil.ByteBuffer)
|
|
|
|
}
|
|
|
|
id++
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
2020-08-14 22:40:51 +00:00
|
|
|
return &bytesutil.ByteBuffer{
|
2020-08-16 19:12:19 +00:00
|
|
|
B: make([]byte, 0, capacityNeeded),
|
2020-08-14 22:40:51 +00:00
|
|
|
}
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Put returns bb to the pool.
|
|
|
|
func Put(bb *bytesutil.ByteBuffer) {
|
|
|
|
capacity := cap(bb.B)
|
2021-03-14 20:56:23 +00:00
|
|
|
id, poolCapacity := getPoolIDAndCapacity(capacity)
|
|
|
|
if capacity <= poolCapacity {
|
|
|
|
bb.Reset()
|
|
|
|
pools[id].Put(bb)
|
|
|
|
}
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
|
|
|
|
2020-08-28 06:44:08 +00:00
|
|
|
func getPoolIDAndCapacity(size int) (int, int) {
|
2020-08-16 19:12:19 +00:00
|
|
|
size--
|
2020-08-13 20:12:22 +00:00
|
|
|
if size < 0 {
|
|
|
|
size = 0
|
|
|
|
}
|
2024-06-13 14:56:23 +00:00
|
|
|
size >>= 6
|
2020-08-16 19:12:19 +00:00
|
|
|
id := bits.Len(uint(size))
|
2021-03-14 20:56:23 +00:00
|
|
|
if id >= len(pools) {
|
2020-08-16 19:12:19 +00:00
|
|
|
id = len(pools) - 1
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
2024-06-13 14:56:23 +00:00
|
|
|
return id, (1 << (id + 6))
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|