Skip to content

Commit

Permalink
Avoid allocations with (*regexp.Regexp).MatchString (#602)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
Juneezee authored Oct 29, 2023
1 parent 93a954c commit 12cfd7a
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions gocron.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 12cfd7a

Please sign in to comment.