From 5c2d46805893fb87a057907ac336e260989349a8 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Wed, 18 Oct 2023 23:30:11 +0800 Subject: [PATCH] lib/color: avoid unnecessary byte/string conversion We can use `(*regexp.Regexp).MatchString` instead of `(*regexp.Regexp).Match([]byte(...))` to avoid unnecessary `[]byte` conversions and reduce allocations. Example benchmark: func BenchmarkMatch(b *testing.B) { for i := 0; i < b.N; i++ { if match := themeColorRegex.Match([]byte("N1")); !match { b.Fail() } } } func BenchmarkMatchString(b *testing.B) { for i := 0; i < b.N; i++ { if match := themeColorRegex.MatchString("N1"); !match { b.Fail() } } } goos: linux goarch: amd64 pkg: oss.terrastruct.com/d2/lib/color cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkMatch-16 9894165 114.3 ns/op 2 B/op 1 allocs/op BenchmarkMatchString-16 13439838 83.61 ns/op 0 B/op 0 allocs/op PASS ok oss.terrastruct.com/d2/lib/color 3.306s Signed-off-by: Eng Zer Jun --- lib/color/color.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/color/color.go b/lib/color/color.go index fb5860034..7a54573e6 100644 --- a/lib/color/color.go +++ b/lib/color/color.go @@ -14,7 +14,7 @@ import ( var themeColorRegex = regexp.MustCompile(`^(N[1-7]|B[1-6]|AA[245]|AB[45])$`) func IsThemeColor(colorString string) bool { - return themeColorRegex.Match([]byte(colorString)) + return themeColorRegex.MatchString(colorString) } func Darken(colorString string) (string, error) {