Skip to content

Commit

Permalink
refactor(tmpl): avoid unnecessary byte/string conversion (#4356)
Browse files Browse the repository at this point in the history
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 <engzerjun@gmail.com>
  • Loading branch information
Juneezee committed Oct 10, 2023
1 parent 8203f91 commit 37e3fde
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions internal/tmpl/tmpl.go
Expand Up @@ -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) {
Expand All @@ -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{}
}

Expand Down

0 comments on commit 37e3fde

Please sign in to comment.