Skip to content

Commit 5a86e2e

Browse files
committed
Optimize marshalMapInOrder with strings.Builder
Replace string concatenation with strings.Builder in marshalMapInOrder function to improve performance and reduce memory allocations. Signed-off-by: Sascha Grunert <[email protected]>
1 parent c049207 commit 5a86e2e

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

cmd/crictl/util.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -490,10 +490,14 @@ func parseLabelStringSlice(ss []string) (map[string]string, error) {
490490
// marshalMapInOrder marshals a map into JSON in the order of the original
491491
// data structure.
492492
func marshalMapInOrder(m map[string]any, t any) (string, error) {
493-
s := "{"
493+
var sb strings.Builder
494+
sb.WriteString("{")
494495

495496
v := reflect.ValueOf(t)
496-
for i := range v.Type().NumField() {
497+
numFields := v.Type().NumField()
498+
fieldCount := 0
499+
500+
for i := range numFields {
497501
field := jsonFieldFromTag(v.Type().Field(i).Tag)
498502
if field == "" || field == "-" {
499503
continue
@@ -504,15 +508,20 @@ func marshalMapInOrder(m map[string]any, t any) (string, error) {
504508
return "", err
505509
}
506510

507-
s += fmt.Sprintf("%q:%s,", field, value)
511+
if fieldCount > 0 {
512+
sb.WriteString(",")
513+
}
514+
515+
fmt.Fprintf(&sb, "%q:%s", field, value)
516+
517+
fieldCount++
508518
}
509519

510-
s = s[:len(s)-1]
511-
s += "}"
520+
sb.WriteString("}")
512521

513522
var buf bytes.Buffer
514523

515-
if err := json.Indent(&buf, []byte(s), "", " "); err != nil {
524+
if err := json.Indent(&buf, []byte(sb.String()), "", " "); err != nil {
516525
return "", err
517526
}
518527

0 commit comments

Comments
 (0)