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 <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2023-10-18 23:30:11 +08:00
parent a3a685d96f
commit 5c2d468058
No known key found for this signature in database
GPG key ID: DAEBBD2E34C111E6

View file

@ -14,7 +14,7 @@ import (
var themeColorRegex = regexp.MustCompile(`^(N[1-7]|B[1-6]|AA[245]|AB[45])$`) var themeColorRegex = regexp.MustCompile(`^(N[1-7]|B[1-6]|AA[245]|AB[45])$`)
func IsThemeColor(colorString string) bool { func IsThemeColor(colorString string) bool {
return themeColorRegex.Match([]byte(colorString)) return themeColorRegex.MatchString(colorString)
} }
func Darken(colorString string) (string, error) { func Darken(colorString string) (string, error) {