Created
December 19, 2013 15:24
-
-
Save rdarder/8040886 to your computer and use it in GitHub Desktop.
benchmark passing structs vs pointers vs mixed (first level struct, second level pointer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package smap | |
import ( | |
"bytes" | |
"testing" | |
) | |
type skey string | |
func (s skey) Cmp(other Key) int { | |
return bytes.Compare([]byte(string(s)), []byte(string(other.(skey)))) | |
} | |
type PInterval struct { | |
From, To *Edge | |
} | |
func valueReceiver(i Interval) Interval { | |
i.From.Key.Cmp(i.To.Key) | |
return i | |
} | |
func mixedReceiver(i PInterval) PInterval { | |
i.From.Key.Cmp(i.To.Key) | |
return i | |
} | |
func pointerReceiver(i *PInterval) *PInterval { | |
i.From.Key.Cmp(i.To.Key) | |
return i | |
} | |
func BenchmarkByValue(b *testing.B) { | |
I := Interval{Edge{skey("hello"), false}, Edge{skey("world"), false}} | |
var got Interval | |
for i := 0; i < b.N; i++ { | |
got = valueReceiver(I) | |
} | |
var _ = got | |
} | |
func BenchmarkPointer(b *testing.B) { | |
I := &PInterval{&Edge{skey("hello"), false}, &Edge{skey("world"), false}} | |
var got *PInterval | |
for i := 0; i < b.N; i++ { | |
got = pointerReceiver(I) | |
} | |
var _ = got | |
} | |
func BenchmarkMixed(b *testing.B) { | |
I := PInterval{&Edge{skey("hello"), false}, &Edge{skey("world"), false}} | |
var got PInterval | |
for i := 0; i < b.N; i++ { | |
got = mixedReceiver(I) | |
} | |
var _ = got | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
benchmarks show little difference when there's some work to be done on the arguments. in this case it's a simple Cmp. Usually the work per Interval argument is >> 1
$ go test -bench . -benchmem
testing: warning: no tests to run
PASS
BenchmarkByValue 10000000 187 ns/op 16 B/op 2 allocs/op
BenchmarkPointer 10000000 154 ns/op 16 B/op 2 allocs/op
BenchmarkMixed 10000000 158 ns/op 16 B/op 2 allocs/op