From f20073fbe14d86c10fa2d800ca7e7ec868a83869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Sun, 12 Jan 2025 18:21:18 +0200 Subject: [PATCH] tpl/collections: Use MapRange() in Sort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ``` │ stash.bench │ fix-mapkeys.bench │ │ sec/op │ sec/op vs base │ SortMap-10 1005.0n ± 2% 918.7n ± 0% -8.59% (p=0.002 n=6) │ stash.bench │ fix-mapkeys.bench │ │ B/op │ B/op vs base │ SortMap-10 640.0 ± 0% 512.0 ± 0% -20.00% (p=0.002 n=6) │ stash.bench │ fix-mapkeys.bench │ │ allocs/op │ allocs/op vs base │ SortMap-10 16.00 ± 0% 15.00 ± 0% -6.25% (p=0.002 n=6) ``` --- tpl/collections/sort.go | 19 +++++++++++-------- tpl/collections/sort_test.go | 8 ++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) 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) + } +}