From 6a94085eceddccaf258cb8e384fa4aa6d428aa13 Mon Sep 17 00:00:00 2001 From: Joe Wreschnig Date: Sat, 13 Jun 2020 17:32:04 +0200 Subject: [PATCH 1/1] Improve Error.Error() performance MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit ‘fmt’ is unnecessary to concatenate two strings. `benchcmp` says: BenchmarkError-4 226 65.8 -70.88% --- error.go | 3 +-- error_test.go | 9 +++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) 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) + } + } +} -- 2.20.1