Last active
August 29, 2015 14:10
-
-
Save gom/aeddccd1c31434990ea9 to your computer and use it in GitHub Desktop.
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 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() { | |
} |
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 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) | |
} | |
} |
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
$ 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