Skip to content

Commit 61a9854

Browse files
authored
perf(mempool): Replace sync.Mutex with sync.Once (#13293)
`sync.Once` uses an atomic integer as gate to check if the slab is already initialized and therefore yields a ~9% performance improvement for `get` operations. ``` goos: linux goarch: amd64 pkg: github.com/grafana/loki/v3/pkg/util/mempool cpu: 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz │ bench.old │ bench.new │ │ sec/op │ sec/op vs base │ Slab/1KB-8 138.5n ± 2% 125.1n ± 2% -9.71% (p=0.000 n=10) Slab/1MB-8 140.5n ± 3% 128.1n ± 2% -8.83% (p=0.000 n=10) Slab/128MB-8 143.0n ± 3% 130.4n ± 3% -8.81% (p=0.000 n=10) geomean 140.7n 127.8n -9.12% ``` Signed-off-by: Christian Haudum <[email protected]>
1 parent ede6941 commit 61a9854

File tree

2 files changed

+2
-7
lines changed

2 files changed

+2
-7
lines changed

pkg/util/mempool/pool.go

+2-6
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ var (
2020
type slab struct {
2121
buffer chan unsafe.Pointer
2222
size, count int
23-
mtx sync.Mutex
23+
once sync.Once
2424
metrics *metrics
2525
name string
2626
}
@@ -49,11 +49,7 @@ func (s *slab) init() {
4949

5050
func (s *slab) get(size int) ([]byte, error) {
5151
s.metrics.accesses.WithLabelValues(s.name, opTypeGet).Inc()
52-
s.mtx.Lock()
53-
if s.buffer == nil {
54-
s.init()
55-
}
56-
defer s.mtx.Unlock()
52+
s.once.Do(s.init)
5753

5854
// wait for available buffer on channel
5955
var buf []byte

pkg/util/mempool/pool_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,6 @@ func BenchmarkSlab(b *testing.B) {
124124
} {
125125
b.Run(flagext.ByteSize(uint64(sz)).String(), func(b *testing.B) {
126126
slab := newSlab(sz, 1, newMetrics(nil, "test"))
127-
slab.init()
128127
b.ResetTimer()
129128

130129
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)