Skip to content

Commit eee143e

Browse files
committed
Use sync.Pool to reduce GC pressure
The benchmarks show a reduction in allocs without significant performance regression. Signed-off-by: Cory Snider <[email protected]>
1 parent d7e18d8 commit eee143e

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

mutexmap.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ type lockCtr struct {
2424
waiters atomic.Int32 // Number of callers waiting to acquire the lock
2525
}
2626

27+
var lockCtrPool = sync.Pool{New: func() any { return new(lockCtr) }}
28+
2729
// Lock locks the mutex identified by key.
2830
func (l *MutexMap[T]) Lock(key T) {
2931
l.mu.Lock()
@@ -33,7 +35,7 @@ func (l *MutexMap[T]) Lock(key T) {
3335

3436
nameLock, exists := l.locks[key]
3537
if !exists {
36-
nameLock = &lockCtr{}
38+
nameLock = lockCtrPool.Get().(*lockCtr)
3739
l.locks[key] = nameLock
3840
}
3941

@@ -62,6 +64,7 @@ func (l *MutexMap[T]) Unlock(key T) {
6264

6365
if nameLock.waiters.Load() <= 0 {
6466
delete(l.locks, key)
67+
defer lockCtrPool.Put(nameLock)
6568
}
6669
nameLock.Unlock()
6770
}

0 commit comments

Comments
 (0)