v2ray-core/common/buf/buffer_pool.go

64 lines
1.1 KiB
Go
Raw Normal View History

2016-12-09 11:35:27 +01:00
package buf
2016-04-12 16:52:57 +02:00
import (
"sync"
)
2018-03-11 23:06:04 +01:00
const (
// Size of a regular buffer.
Size = 2 * 1024
)
2016-11-21 22:08:34 +01:00
2018-04-02 22:01:55 +02:00
func createAllocFunc(size int32) func() interface{} {
2018-03-11 23:06:04 +01:00
return func() interface{} {
return make([]byte, size)
2016-11-21 22:08:34 +01:00
}
}
2018-04-01 12:20:32 +02:00
// The following parameters controls the size of buffer pools.
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
// Package buf is guaranteed to not use buffers larger than the largest pool.
// Other packets may use larger buffers.
2018-03-12 16:21:39 +01:00
const (
numPools = 5
sizeMulti = 4
)
var (
2018-04-01 12:20:32 +02:00
pool [numPools]sync.Pool
2018-04-02 22:01:55 +02:00
poolSize [numPools]int32
largeSize int32
2018-03-12 16:21:39 +01:00
)
2016-11-21 22:08:34 +01:00
2018-03-12 16:21:39 +01:00
func init() {
2018-04-02 22:01:55 +02:00
size := int32(Size)
2018-03-12 16:21:39 +01:00
for i := 0; i < numPools; i++ {
2018-03-16 16:22:22 +07:00
pool[i] = sync.Pool{
2018-03-12 16:21:39 +01:00
New: createAllocFunc(size),
}
poolSize[i] = size
2018-04-01 12:20:32 +02:00
largeSize = size
2018-03-12 16:21:39 +01:00
size *= sizeMulti
}
2016-11-21 22:08:34 +01:00
}
2018-04-02 22:01:55 +02:00
func newBytes(size int32) []byte {
2018-03-12 16:21:39 +01:00
for idx, ps := range poolSize {
if size <= ps {
return pool[idx].Get().([]byte)
}
}
return make([]byte, size)
2018-03-11 23:06:04 +01:00
}
2016-05-11 10:54:20 -07:00
2018-03-12 16:21:39 +01:00
func freeBytes(b []byte) {
2018-04-02 22:01:55 +02:00
size := int32(cap(b))
2018-03-12 16:24:31 +01:00
b = b[0:cap(b)]
2018-03-12 16:21:39 +01:00
for i := numPools - 1; i >= 0; i-- {
2018-03-28 22:23:49 +02:00
if size >= poolSize[i] {
2018-05-28 23:05:11 +02:00
pool[i].Put(b) // nolint: megacheck
2018-03-16 16:22:22 +07:00
return
2018-03-12 16:21:39 +01:00
}
}
2018-03-11 23:06:04 +01:00
}