Skip to content

Commit

Permalink
Use sync.OnceValue for lazy regexp initialization
Browse files Browse the repository at this point in the history
Using sync.OnceValue instead of the local implementation brings some
benefits in allocations, panic handling and mutex use / concurrent
access after initialization.

Signed-off-by: Kimmo Lehto <klehto@mirantis.com>
  • Loading branch information
kke committed Jun 13, 2024
1 parent a947377 commit c111ad2
Showing 1 changed file with 3 additions and 8 deletions.
11 changes: 3 additions & 8 deletions regexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,9 @@ const (
)

func lazyRegexCompile(str string) func() *regexp.Regexp {
var regex *regexp.Regexp
var once sync.Once
return func() *regexp.Regexp {
once.Do(func() {
regex = regexp.MustCompile(str)
})
return regex
}
return sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile(str)
})
}

var (
Expand Down

0 comments on commit c111ad2

Please sign in to comment.