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 <dvyukov@google.com>
1 file changed
tree: 95803d98c48c25f1948638a80c9788e261adfdbc
  1. api/
  2. doc/
  3. include/
  4. lib/
  5. misc/
  6. src/
  7. test/
  8. .gitattributes
  9. .gitignore
  10. AUTHORS
  11. CONTRIBUTING.md
  12. CONTRIBUTORS
  13. favicon.ico
  14. LICENSE
  15. PATENTS
  16. README.md
  17. robots.txt
README.md

The Go Programming Language

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Gopher image

For documentation about how to install and use Go, visit https://golang.org/ or load doc/install-source.html in your web browser.

Our canonical Git repository is located at https://go.googlesource.com/go. (There is a mirror of the repository at https://github.com/golang/go.)

Please report issues here: https://golang.org/issue/new

Go is the work of hundreds of contributors. We appreciate your help!

To contribute, please read the contribution guidelines: https://golang.org/doc/contribute.html

Please note that we do not use pull requests.

Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.


Binary Distribution Notes

If you have just untarred a binary Go distribution, you need to set the environment variable $GOROOT to the full path of the go directory (the one containing this file). You can omit the variable if you unpack it into /usr/local/go, or if you rebuild from sources by running all.bash (see doc/install-source.html). You should also add the Go binary directory $GOROOT/bin to your shell's path.

For example, if you extracted the tar file into $HOME/go, you might put the following in your .profile:

export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin

See https://golang.org/doc/install or doc/install.html for more details.