Skip to content

Commit bd043d8

Browse files
evanphxdvyukov
authored andcommitted
expvar: Use sync/atomic to manipulate Int for better perf
Using a mutex to protect a single int operation is quite heavyweight. Using sync/atomic provides much better performance. This change was benchmarked as such: BenchmarkSync 10000000 139 ns/op BenchmarkAtomic 200000000 9.90 ns/op package blah import ( "sync" "sync/atomic" "testing" ) type Int struct { mu sync.RWMutex i int64 } func (v *Int) Add(delta int64) { v.mu.Lock() defer v.mu.Unlock() v.i += delta } type AtomicInt struct { i int64 } func (v *AtomicInt) Add(delta int64) { atomic.AddInt64(&v.i, delta) } func BenchmarkSync(b *testing.B) { s := new(Int) for i := 0; i < b.N; i++ { s.Add(1) } } func BenchmarkAtomic(b *testing.B) { s := new(AtomicInt) for i := 0; i < b.N; i++ { s.Add(1) } } Change-Id: I6998239c785967647351bbfe8533c38e4894543b Reviewed-on: https://go-review.googlesource.com/3430 Reviewed-by: Dmitry Vyukov <[email protected]>
1 parent b49c3ac commit bd043d8

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

src/expvar/expvar.go

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import (
3232
"sort"
3333
"strconv"
3434
"sync"
35+
"sync/atomic"
3536
)
3637

3738
// Var is an abstract type for all exported variables.
@@ -41,26 +42,19 @@ type Var interface {
4142

4243
// Int is a 64-bit integer variable that satisfies the Var interface.
4344
type Int struct {
44-
mu sync.RWMutex
45-
i int64
45+
i int64
4646
}
4747

4848
func (v *Int) String() string {
49-
v.mu.RLock()
50-
defer v.mu.RUnlock()
51-
return strconv.FormatInt(v.i, 10)
49+
return strconv.FormatInt(atomic.LoadInt64(&v.i), 10)
5250
}
5351

5452
func (v *Int) Add(delta int64) {
55-
v.mu.Lock()
56-
defer v.mu.Unlock()
57-
v.i += delta
53+
atomic.AddInt64(&v.i, delta)
5854
}
5955

6056
func (v *Int) Set(value int64) {
61-
v.mu.Lock()
62-
defer v.mu.Unlock()
63-
v.i = value
57+
atomic.StoreInt64(&v.i, value)
6458
}
6559

6660
// Float is a 64-bit float variable that satisfies the Var interface.

0 commit comments

Comments
 (0)