Skip to content

Commit

Permalink
Improve NewMember performance by ~9x
Browse files Browse the repository at this point in the history
goos: linux
goarch: amd64
pkg: go.opentelemetry.io/otel/baggage
cpu: AMD EPYC 7B13
             │ /tmp/old.txt  │            /tmp/new.txt             │
             │    sec/op     │   sec/op     vs base                │
NewMember-96   368.20n ± 21%   46.94n ± 3%  -87.25% (p=0.000 n=10)
  • Loading branch information
cdvr1993 committed Dec 5, 2023
1 parent 6cee2b4 commit eddc838
Showing 1 changed file with 48 additions and 2 deletions.
50 changes: 48 additions & 2 deletions baggage/baggage.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,15 @@ const (
keyValueDelimiter = "="
propertyDelimiter = ";"

// if you update these 2 values you must update the static implementation below: keyReValidator and valReValidator
keyDef = `([\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+)`
valueDef = `([\x21\x23-\x2b\x2d-\x3a\x3c-\x5B\x5D-\x7e]*)`
keyValueDef = `\s*` + keyDef + `\s*` + keyValueDelimiter + `\s*` + valueDef + `\s*`
)

var (
keyRe = regexp.MustCompile(`^` + keyDef + `$`)
valueRe = regexp.MustCompile(`^` + valueDef + `$`)
keyRe = keyReValidator{}
valueRe = valReValidator{}
propertyRe = regexp.MustCompile(`^(?:\s*` + keyDef + `\s*|` + keyValueDef + `)$`)
)

Expand Down Expand Up @@ -550,3 +551,48 @@ func (b Baggage) String() string {
}
return strings.Join(members, listDelimiter)
}

// They must follow the following rules (regex syntax):
// keyDef = `([\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+)`
// valueDef = `([\x21\x23-\x2b\x2d-\x3a\x3c-\x5B\x5D-\x7e]*)`
type keyReValidator struct{}

func (keyReValidator) MatchString(s string) bool {
if len(s) == 0 {
return false
}

for _, c := range s {
if !(c >= 0x23 && c <= 0x27) &&
!(c >= 0x30 && c <= 0x39) &&
!(c >= 0x41 && c <= 0x5a) &&
!(c >= 0x5e && c <= 0x7a) &&
c != 0x21 &&
c != 0x2a &&
c != 0x2b &&
c != 0x2d &&
c != 0x2e &&
c != 0x7c &&
c != 0x7e {
return false
}
}

return true
}

type valReValidator struct{}

func (valReValidator) MatchString(s string) bool {
for _, c := range s {
if !(c >= 0x23 && c <= 0x2b) &&
!(c >= 0x2d && c <= 0x3a) &&
!(c >= 0x3c && c <= 0x5b) &&
!(c >= 0x5d && c <= 0x7e) &&
c != 0x21 {
return false
}
}

return true
}

0 comments on commit eddc838

Please sign in to comment.