Skip to content

Instantly share code, notes, and snippets.

@smithjessk
Last active October 4, 2016 14:40
Show Gist options
  • Save smithjessk/c5dc833c4eaf09f252c529ccd387bef4 to your computer and use it in GitHub Desktop.
Save smithjessk/c5dc833c4eaf09f252c529ccd387bef4 to your computer and use it in GitHub Desktop.
Times error handling via panics vs. if statements
package bench
import (
"errors"
"os"
"testing"
)
func TestMain(m *testing.M) {
code := m.Run()
os.Exit(code)
}
func BenchmarkPanic(b *testing.B) {
for i := 0; i < b.N; i++ {
somethingThatPanics()
}
}
func somethingThatPanics() {
defer somethingThatRecovers()
panic(errors.New("Rob Pike made me do it!"))
}
func somethingThatRecovers() {
if r := recover(); r != nil {
return
}
}
func BenchmarkIfError(t *testing.B) {
for i := 0; i < t.N; i++ {
err := somethingThatReturnsAnError()
if err != nil {
continue
}
}
}
func somethingThatReturnsAnError() error {
return errors.New("Rob Pike made me do it!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment