Skip to content

Instantly share code, notes, and snippets.

@ttacon
Last active August 29, 2015 14:06
Show Gist options
  • Save ttacon/757bdf2b6ae5bc1322c7 to your computer and use it in GitHub Desktop.
Save ttacon/757bdf2b6ae5bc1322c7 to your computer and use it in GitHub Desktop.
Switch on type vs type assertion
package typeassertion
import (
"errors"
"testing"
)
// go test -bench=. -benchtime 20s
//
// Benchmark_SwitchType 100000000 483 ns/op
// Benchmark_TypeAssertion 100000000 442 ns/op
var issues = []interface{}{
errors.New("an error"),
0,
errors.New("an error 0"),
1,
errors.New("an error 1"),
2,
errors.New("an error 2"),
3,
errors.New("an error 3"),
4,
-1,
errors.New("an error 4"),
5,
errors.New("an error 5"),
6,
errors.New("an error 6"),
7,
errors.New("an error 7"),
8,
errors.New("an error 8"),
9,
errors.New("an error 9"),
}
func Benchmark_SwitchType(b *testing.B) {
var lastError int
for i := 0; i < b.N; i++ {
for j, issue := range issues {
switch issue.(type) {
case error:
lastError = j
default:
}
}
}
lastError++
}
func Benchmark_TypeAssertion(b *testing.B) {
var lastError int
for i := 0; i < b.N; i++ {
for j, issue := range issues {
if _, ok := issue.(error); ok {
lastError = j
}
}
}
lastError++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment