Skip to content

Commit 7850004

Browse files
committed
No allocation
Signed-off-by: Alan Protasio <[email protected]>
1 parent 2a33354 commit 7850004

File tree

3 files changed

+14
-11
lines changed

3 files changed

+14
-11
lines changed

pkg/cortexpb/slicesPool.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,28 @@ func (sp *byteSlicePools) init(pools int) {
2121
size := int(math.Pow(2, float64(i)))
2222
sp.pools[i] = sync.Pool{
2323
New: func() interface{} {
24-
return make([]byte, 0, size)
24+
buf := make([]byte, 0, size)
25+
return &buf
2526
},
2627
}
2728
}
2829
}
2930

30-
func (sp *byteSlicePools) getSlice(size int) []byte {
31+
func (sp *byteSlicePools) getSlice(size int) *[]byte {
3132
index := int(math.Ceil(math.Log2(float64(size))))
3233

3334
if index < 0 || index >= len(sp.pools) {
34-
return make([]byte, size)
35+
buf := make([]byte, size)
36+
return &buf
3537
}
3638

37-
s := sp.pools[index].Get().([]byte)
38-
return s[:size]
39+
s := sp.pools[index].Get().(*[]byte)
40+
*s = (*s)[:size]
41+
return s
3942
}
4043

41-
func (sp *byteSlicePools) reuseSlice(s []byte) {
42-
index := int(math.Floor(math.Log2(float64(cap(s)))))
44+
func (sp *byteSlicePools) reuseSlice(s *[]byte) {
45+
index := int(math.Floor(math.Log2(float64(cap(*s)))))
4346

4447
if index < 0 || index >= len(sp.pools) {
4548
return

pkg/cortexpb/slicesPool_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ func TestByteSlicePools(t *testing.T) {
1010
sut := newSlicePool(20)
1111
for i := 0; i < 1024*1024; i = i + 128 {
1212
s := sut.getSlice(i)
13-
assert.Equal(t, len(s), i)
13+
assert.Equal(t, len(*s), i)
1414
sut.reuseSlice(s)
1515
}
1616
}

pkg/cortexpb/timeseries.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func (PreallocConfig) RegisterFlags(f *flag.FlagSet) {
6262
// PreallocWriteRequest is a WriteRequest which preallocs slices on Unmarshal.
6363
type PreallocWriteRequest struct {
6464
WriteRequest
65-
data []byte
65+
data *[]byte
6666
}
6767

6868
// Unmarshal implements proto.Message.
@@ -84,8 +84,8 @@ func (p *PreallocTimeseries) Unmarshal(dAtA []byte) error {
8484

8585
func (p *PreallocWriteRequest) Marshal() (dAtA []byte, err error) {
8686
size := p.Size()
87-
dAtA = bytePool.getSlice(size)
88-
p.data = dAtA
87+
p.data = bytePool.getSlice(size)
88+
dAtA = *p.data
8989
n, err := p.MarshalToSizedBuffer(dAtA[:size])
9090
if err != nil {
9191
return nil, err

0 commit comments

Comments
 (0)