Skip to content

Commit

Permalink
Merge pull request #719 from tdakkota/perf/uri-preallocate
Browse files Browse the repository at this point in the history
perf(uri): preallocate `encodeObject` buffer
  • Loading branch information
ernado authored Dec 13, 2022
2 parents 681334b + 290e329 commit ad15ce2
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion uri/header_param_encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func (e *headerParamEncoder) serialize() {
e.header.Set(e.paramName, strings.Join(e.items, ","))
return
case typeObject:
kvSep, fieldSep := ',', ','
var kvSep, fieldSep byte = ',', ','
if e.explode {
kvSep = '='
}
Expand Down
22 changes: 18 additions & 4 deletions uri/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,28 @@ type Field struct {
Value string
}

func encodeObject(kvSep, fieldSep rune, fields []Field) string {
var sb strings.Builder
func encodeObject(kvSep, fieldSep byte, fields []Field) string {
var (
sb strings.Builder
size int
)
// Preallocate the buffer.
{
for _, f := range fields {
size += len(f.Name) + len(f.Value) + 2
}
if len(fields) == 1 {
// If there are less than 2 fields, we don't need to add the field separator.
size--
}
}
sb.Grow(size)
for i, f := range fields {
if i > 0 {
sb.WriteRune(fieldSep)
sb.WriteByte(fieldSep)
}
sb.WriteString(f.Name)
sb.WriteRune(kvSep)
sb.WriteByte(kvSep)
sb.WriteString(f.Value)
}
return sb.String()
Expand Down
2 changes: 1 addition & 1 deletion uri/path_encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (e *PathEncoder) object() string {
return encodeObject(kvSep, fieldSep, e.fields)

case PathStyleLabel:
kvSep, fieldSep := ',', ','
var kvSep, fieldSep byte = ',', ','
if e.explode {
kvSep, fieldSep = '=', '.'
}
Expand Down

0 comments on commit ad15ce2

Please sign in to comment.