Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing interface overhead.
$ go test -gcflags=-l -bench=.
testing: warning: no tests to run
PASS
BenchmarkDirect-4 500000000 3.36 ns/op
BenchmarkInterface-4 1000000000 3.46 ns/op
ok misc/intb 5.830s
package main
import "testing"
type Int int64
func (i *Int) Sum(i2 Int) { (*i) += i2 }
type Summer interface {
Sum(i Int)
}
func BenchmarkDirect(b *testing.B) {
var o Int
addVal := Int(18)
for i := 0; i < b.N; i++ {
o.Sum(addVal)
}
if int(o) != b.N*int(addVal) {
b.Errorf("got %v after %v iterations, wanted %v", o, b.N, b.N*int(addVal))
}
}
func BenchmarkInterface(b *testing.B) {
var p Int
o := Summer(&p)
addVal := Int(18)
for i := 0; i < b.N; i++ {
o.Sum(addVal)
}
if int(p) != b.N*int(addVal) {
b.Errorf("got %v after %v iterations, wanted %v", o, b.N, b.N*int(addVal))
}
}
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkDirect-4 500000000 2.34 ns/op
BenchmarkInterface-4 500000000 3.85 ns/op
ok misc/intb 3.809s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment