Skip to content

Commit

Permalink
perf(mempool): Replace sync.Mutex with sync.Once (#13293)
Browse files Browse the repository at this point in the history
`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 <christian.haudum@gmail.com>
  • Loading branch information
chaudum authored Jun 24, 2024
1 parent ede6941 commit 61a9854
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 7 deletions.
8 changes: 2 additions & 6 deletions pkg/util/mempool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var (
type slab struct {
buffer chan unsafe.Pointer
size, count int
mtx sync.Mutex
once sync.Once
metrics *metrics
name string
}
Expand Down Expand Up @@ -49,11 +49,7 @@ func (s *slab) init() {

func (s *slab) get(size int) ([]byte, error) {
s.metrics.accesses.WithLabelValues(s.name, opTypeGet).Inc()
s.mtx.Lock()
if s.buffer == nil {
s.init()
}
defer s.mtx.Unlock()
s.once.Do(s.init)

// wait for available buffer on channel
var buf []byte
Expand Down
1 change: 0 additions & 1 deletion pkg/util/mempool/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ func BenchmarkSlab(b *testing.B) {
} {
b.Run(flagext.ByteSize(uint64(sz)).String(), func(b *testing.B) {
slab := newSlab(sz, 1, newMetrics(nil, "test"))
slab.init()
b.ResetTimer()

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

0 comments on commit 61a9854

Please sign in to comment.