diff --git a/uri/header_param_encoder.go b/uri/header_param_encoder.go index 39e450574..a03097b72 100644 --- a/uri/header_param_encoder.go +++ b/uri/header_param_encoder.go @@ -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 = '=' } diff --git a/uri/object.go b/uri/object.go index b7e1e087e..330186359 100644 --- a/uri/object.go +++ b/uri/object.go @@ -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() diff --git a/uri/path_encoder.go b/uri/path_encoder.go index 5a2dc5318..91a7040cd 100644 --- a/uri/path_encoder.go +++ b/uri/path_encoder.go @@ -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 = '=', '.' }