diff --git a/tpl/collections/sort.go b/tpl/collections/sort.go index 2040f8490c5..8a547a1f8ba 100644 --- a/tpl/collections/sort.go +++ b/tpl/collections/sort.go @@ -99,16 +99,18 @@ func (ns *Namespace) Sort(ctx context.Context, l any, args ...any) (any, error) } case reflect.Map: - keys := seqv.MapKeys() - for i := 0; i < seqv.Len(); i++ { - p.Pairs[i].Value = seqv.MapIndex(keys[i]) - + iter := seqv.MapRange() + k := 0 + for iter.Next() { + key := iter.Key() + value := iter.Value() + p.Pairs[k].Value = value if sortByField == "" { - p.Pairs[i].Key = keys[i] + p.Pairs[k].Key = key } else if sortByField == "value" { - p.Pairs[i].Key = p.Pairs[i].Value + p.Pairs[k].Key = p.Pairs[k].Value } else { - v := p.Pairs[i].Value + v := p.Pairs[k].Value var err error for i, elemName := range path { v, err = evaluateSubElem(ctxv, v, elemName) @@ -124,8 +126,9 @@ func (ns *Namespace) Sort(ctx context.Context, l any, args ...any) (any, error) break } } - p.Pairs[i].Key = v + p.Pairs[k].Key = v } + k++ } } diff --git a/tpl/collections/sort_test.go b/tpl/collections/sort_test.go index 1ec95882f69..cc45819213d 100644 --- a/tpl/collections/sort_test.go +++ b/tpl/collections/sort_test.go @@ -261,3 +261,11 @@ func TestSort(t *testing.T) { }) } } + +func BenchmarkSortMap(b *testing.B) { + ns := newNs() + m := map[string]int{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50} + for i := 0; i < b.N; i++ { + ns.Sort(context.Background(), m) + } +}