Skip to content

Instantly share code, notes, and snippets.

@linxGnu
Created June 9, 2020 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linxGnu/8c093f7f6a4a1deb6045d7d27677263f to your computer and use it in GitHub Desktop.
Save linxGnu/8c093f7f6a4a1deb6045d7d27677263f to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"sync"
"sync/atomic"
"testing"
)
func BenchmarkAtomicValue(b *testing.B) {
v := &atomic.Value{}
var buf bytes.Buffer
s := "Target"
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
v.Store(&s)
buf.WriteString(*v.Load().(*string))
}
}
}
type MutexValue struct {
mu sync.Mutex
val string
}
func (v *MutexValue) Val() string {
v.mu.Lock()
defer v.mu.Unlock()
return v.val
}
func (v *MutexValue) SetVal(val string) {
v.mu.Lock()
defer v.mu.Unlock()
v.val = val
}
func BenchmarkMutex(b *testing.B) {
v := &MutexValue{}
var buf bytes.Buffer
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
v.SetVal("Target")
buf.WriteString(v.Val())
}
}
}
type MutexValueWithoutDefer struct {
mu sync.Mutex
val string
}
func (v *MutexValueWithoutDefer) Val() string {
v.mu.Lock()
val := v.val
v.mu.Unlock()
return val
}
func (v *MutexValueWithoutDefer) SetVal(val string) {
v.mu.Lock()
v.val = val
v.mu.Unlock()
}
func BenchmarkMutexWithoutDefer(b *testing.B) {
v := &MutexValueWithoutDefer{}
var buf bytes.Buffer
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
v.SetVal("Target")
buf.WriteString(v.Val())
}
}
}
type RWMutexValue struct {
mu sync.RWMutex
val string
}
func (v *RWMutexValue) Val() string {
v.mu.RLock()
defer v.mu.RUnlock()
return v.val
}
func (v *RWMutexValue) SetVal(val string) {
v.mu.Lock()
defer v.mu.Unlock()
v.val = val
}
func BenchmarkRWMutex(b *testing.B) {
v := &RWMutexValue{}
var buf bytes.Buffer
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
v.SetVal("Target")
buf.WriteString(v.Val())
}
}
}
type RWMutexValueWithoutDefer struct {
mu sync.RWMutex
val string
}
func (v *RWMutexValueWithoutDefer) Val() string {
v.mu.RLock()
val := v.val
v.mu.RUnlock()
return val
}
func (v *RWMutexValueWithoutDefer) SetVal(val string) {
v.mu.Lock()
v.val = val
v.mu.Unlock()
}
func BenchmarkRWMutexWithoutDefer(b *testing.B) {
v := &RWMutexValueWithoutDefer{}
var buf bytes.Buffer
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
v.SetVal("Target")
buf.WriteString(v.Val())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment