Skip to content

Instantly share code, notes, and snippets.

@woodsaj
Created August 17, 2016 07:12
Show Gist options
  • Save woodsaj/40a0dec0a1b7f4109c580ef2ade0c829 to your computer and use it in GitHub Desktop.
Save woodsaj/40a0dec0a1b7f4109c580ef2ade0c829 to your computer and use it in GitHub Desktop.
ptr vs value benchmark
package main
import (
"testing"
"strconv"
)
type Data struct {
Name string
Tags []string
}
type MapWithPtrs struct {
Items map[int]*Data
}
type MapWithoutPtrs struct {
Items map[int]Data
}
var (
mwp *MapWithPtrs
mwop *MapWithoutPtrs
)
func init() {
mwp = &MapWithPtrs{
Items: make(map[int]*Data),
}
for i:=0; i < 5000000; i++ {
mwp.Items[i] = &Data{
Name: "data"+strconv.Itoa(i),
Tags: []string{"foo", "baz", "bar", "one", "two", "three", "tag"+strconv.Itoa(i)},
}
}
mwop = &MapWithoutPtrs{
Items: make(map[int]Data),
}
for i:=0; i < 5000000; i++ {
mwop.Items[i] = Data{
Name: "data"+strconv.Itoa(i),
Tags: []string{"foo", "baz", "bar", "one", "two", "three", "tag"+strconv.Itoa(i)},
}
}
}
func BenchmarkPtr(b *testing.B) {
for n:=0; n <b.N; n++ {
if data, ok := mwp.Items[n]; ok {
data.Tags = append(data.Tags, "blah")
}
}
}
func BenchmarkNoPtr(b *testing.B) {
for n:=0; n <b.N; n++ {
if data, ok := mwop.Items[n]; ok {
data.Tags = append(data.Tags, "blah")
mwop.Items[n] = data
}
}
}
@Dieterbe
Copy link

same outcome when I change BenchmarkListPtr to use

    for i := 1; i <= times; i++ {
        for n := 0; n < b.N; n++ {
            lwp[n].Tags = append(lwp[n].Tags, "blah")
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment