Skip to content

Commit

Permalink
Lazily initialize postcode regexes to speed up init()
Browse files Browse the repository at this point in the history
Using `GODEBUG=inittrace=1` I found a relatively constant
10ms init caused by this function.
  • Loading branch information
kylecarbs committed Apr 1, 2024
1 parent a0f74b0 commit cf222ac
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
1 change: 1 addition & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -1364,6 +1364,7 @@ func isPostcodeByIso3166Alpha2(fl FieldLevel) bool {
field := fl.Field()
param := fl.Param()

postcodeRegexInit.Do(initPostcodes)
reg, found := postCodeRegexDict[param]
if !found {
return false
Expand Down
12 changes: 9 additions & 3 deletions postcode_regexes.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package validator

import "regexp"
import (
"regexp"
"sync"
)

var postCodePatternDict = map[string]string{
"GB": `^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$`,
Expand Down Expand Up @@ -164,9 +167,12 @@ var postCodePatternDict = map[string]string{
"YT": `^976\d{2}$`,
}

var postCodeRegexDict = map[string]*regexp.Regexp{}
var (
postcodeRegexInit sync.Once
postCodeRegexDict = map[string]*regexp.Regexp{}
)

func init() {
func initPostcodes() {
for countryCode, pattern := range postCodePatternDict {
postCodeRegexDict[countryCode] = regexp.MustCompile(pattern)
}
Expand Down

0 comments on commit cf222ac

Please sign in to comment.