From: Joe Wreschnig Date: Sat, 13 Jun 2020 15:32:04 +0000 (+0200) Subject: Improve Error.Error() performance X-Git-Url: https://git.korewanetadesu.com/?p=go-signalcontext.git;a=commitdiff_plain;h=6a94085eceddccaf258cb8e384fa4aa6d428aa13 Improve Error.Error() performance ‘fmt’ is unnecessary to concatenate two strings. `benchcmp` says: BenchmarkError-4 226 65.8 -70.88% --- diff --git a/error.go b/error.go index c0a4f97..ac99fec 100644 --- a/error.go +++ b/error.go @@ -1,7 +1,6 @@ package signalcontext import ( - "fmt" "os" ) @@ -16,5 +15,5 @@ func (e Error) Error() string { } func (e Error) String() string { - return fmt.Sprintf("received signal: %s", e.Signal) + return "received signal: " + e.Signal.String() } diff --git a/error_test.go b/error_test.go index eb347ef..dc90e0e 100644 --- a/error_test.go +++ b/error_test.go @@ -11,3 +11,12 @@ func TestError(t *testing.T) { assert.EqualError(t, Error{os.Interrupt}, "received signal: "+os.Interrupt.String()) } + +func BenchmarkError(b *testing.B) { + expected := "received signal: " + os.Interrupt.String() + for i := 0; i < b.N; i++ { + if s := (Error{os.Interrupt}).String(); s != expected { + b.Fatalf("expected %s, got %s", s, expected) + } + } +}