Skip to content

Instantly share code, notes, and snippets.

@gom
Last active August 29, 2015 14:10
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 gom/aeddccd1c31434990ea9 to your computer and use it in GitHub Desktop.
Save gom/aeddccd1c31434990ea9 to your computer and use it in GitHub Desktop.
package main
type Spannable interface {
Len() int
}
type MyString struct {
v string
}
type MyStringPointer struct {
v *string
}
func (s *MyString) Len() int {
return len(s.v)
}
func (p *MyStringPointer) Len() int {
return len(*p.v)
}
func span(s Spannable) int {
return s.Len()
}
func ss(s *MyString) int {
return s.Len()
}
func l(s string) int {
return len(s)
}
func cast(s interface{}) int {
switch s := s.(type) {
case string:
return len(s)
case *string:
return len(*s)
default:
panic("unexpected type!")
}
}
func main() {
}
package main
import "testing"
func BenchmarkInterfaceString(b *testing.B) {
s := &MyString{"foo"}
for i := 0; i < b.N; i++ {
span(s)
}
}
func BenchmarkTypeHintString(b *testing.B) {
s := &MyString{"foo"}
for i := 0; i < b.N; i++ {
ss(s)
}
}
func BenchmarkTypeSwitchString(b *testing.B) {
s := &MyString{"foo"}
for i := 0; i < b.N; i++ {
cast(s.v)
}
}
func BenchmarkInterfaceStringPointer(b *testing.B) {
ss := "foo"
s := &MyStringPointer{&ss}
for i := 0; i < b.N; i++ {
span(s)
}
}
func BenchmarkTypeSwitchStringPointer(b *testing.B) {
ss := "foo"
s := &MyStringPointer{&ss}
for i := 0; i < b.N; i++ {
cast(s.v)
}
}
func BenchmarkNative(b *testing.B) {
s := "foo"
for i := 0; i < b.N; i++ {
l(s)
}
}
$ go test -bench .
testing: warning: no tests to run
PASS
BenchmarkInterfaceString 100000000 12.3 ns/op
BenchmarkTypeSwitchString 20000000 201 ns/op
BenchmarkInterfaceStringPointer 100000000 14.9 ns/op
BenchmarkTypeSwitchStringPointer 50000000 36.4 ns/op
BenchmarkNative 2000000000 1.49 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment