From 12cfd7aaea743d105cbd350919748b02ed14af51 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Mon, 30 Oct 2023 06:14:05 +0800 Subject: [PATCH] Avoid allocations with `(*regexp.Regexp).MatchString` (#602) We should use `(*regexp.Regexp).MatchString` instead of `(*regexp.Regexp).Match([]byte(...))` when matching string to avoid unnecessary `[]byte` conversions and reduce allocations. Example benchmark: func BenchmarkMatch(b *testing.B) { for i := 0; i < b.N; i++ { if match := timeWithSeconds.Match([]byte("06:18:01")); !match { b.Fail() } } } func BenchmarkMatchString(b *testing.B) { for i := 0; i < b.N; i++ { if match := timeWithSeconds.MatchString("06:18:01"); !match { b.Fail() } } } goos: linux goarch: amd64 pkg: github.com/go-co-op/gocron cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkMatch-16 7213512 223.8 ns/op 8 B/op 1 allocs/op BenchmarkMatchString-16 8484169 145.8 ns/op 0 B/op 0 allocs/op PASS ok github.com/go-co-op/gocron 4.114s Signed-off-by: Eng Zer Jun --- gocron.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gocron.go b/gocron.go index 3203d563..def4383d 100644 --- a/gocron.go +++ b/gocron.go @@ -136,9 +136,9 @@ func getFunctionNameOfPointer(fn interface{}) string { func parseTime(t string) (hour, min, sec int, err error) { var timeLayout string switch { - case timeWithSeconds.Match([]byte(t)): + case timeWithSeconds.MatchString(t): timeLayout = "15:04:05" - case timeWithoutSeconds.Match([]byte(t)): + case timeWithoutSeconds.MatchString(t): timeLayout = "15:04" default: return 0, 0, 0, ErrUnsupportedTimeFormat