From 37e3fdee5524f81d35bc70370c90bbecc11c7f14 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Tue, 10 Oct 2023 20:54:44 +0800 Subject: [PATCH] refactor(tmpl): avoid unnecessary byte/string conversion (#4356) We can use `(*regexp.Regexp).MatchString` instead of `(*regexp.Regexp).Match([]byte(...))` to avoid unnecessary `[]byte` conversions and reduce allocations. A one-line change for free performance gain. Benchmark: ```go func BenchmarkMatch(b *testing.B) { for i := 0; i < b.N; i++ { if match := envOnlyRe.Match([]byte("{{ .Env.FOO }}")); !match { b.Fail() } } } func BenchmarkMatchString(b *testing.B) { for i := 0; i < b.N; i++ { if match := envOnlyRe.MatchString("{{ .Env.FOO }}"); !match { b.Fail() } } } ``` Result: ``` goos: linux goarch: amd64 pkg: github.com/goreleaser/goreleaser/internal/tmpl cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkMatch-16 4320873 381.2 ns/op 16 B/op 1 allocs/op BenchmarkMatchString-16 5973543 203.9 ns/op 0 B/op 0 allocs/op PASS ok github.com/goreleaser/goreleaser/internal/tmpl 3.366s ``` Signed-off-by: Eng Zer Jun --- internal/tmpl/tmpl.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/tmpl/tmpl.go b/internal/tmpl/tmpl.go index 5aa652f78..8d9c732e6 100644 --- a/internal/tmpl/tmpl.go +++ b/internal/tmpl/tmpl.go @@ -260,6 +260,8 @@ func (e ExpectedSingleEnvErr) Error() string { return "expected {{ .Env.VAR_NAME }} only (no plain-text or other interpolation)" } +var envOnlyRe = regexp.MustCompile(`^{{\s*\.Env\.[^.\s}]+\s*}}$`) + // ApplySingleEnvOnly enforces template to only contain a single environment variable // and nothing else. func (t *Template) ApplySingleEnvOnly(s string) (string, error) { @@ -272,8 +274,7 @@ func (t *Template) ApplySingleEnvOnly(s string) (string, error) { // but regexp reduces the complexity and should be sufficient, // given the context is mostly discouraging users from bad practice // of hard-coded credentials, rather than catch all possible cases - envOnlyRe := regexp.MustCompile(`^{{\s*\.Env\.[^.\s}]+\s*}}$`) - if !envOnlyRe.Match([]byte(s)) { + if !envOnlyRe.MatchString(s) { return "", ExpectedSingleEnvErr{} }