Improve Error.Error() performance
authorJoe Wreschnig <joe.wreschnig@gmail.com>
Sat, 13 Jun 2020 15:32:04 +0000 (17:32 +0200)
committerJoe Wreschnig <joe.wreschnig@gmail.com>
Sun, 14 Jun 2020 13:50:00 +0000 (15:50 +0200)
‘fmt’ is unnecessary to concatenate two strings. `benchcmp` says:

    BenchmarkError-4               226           65.8          -70.88%

error.go
error_test.go

index c0a4f97..ac99fec 100644 (file)
--- 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()
 }
index eb347ef..dc90e0e 100644 (file)
@@ -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)
+               }
+       }
+}