Skip to content

Commit

Permalink
tpl/collections: Use MapRange() in Sort
Browse files Browse the repository at this point in the history
```
           │ 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)
```
  • Loading branch information
bep committed Jan 12, 2025
1 parent acb4c5f commit 0b64fae
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
19 changes: 11 additions & 8 deletions tpl/collections/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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++
}
}

Expand Down
8 changes: 8 additions & 0 deletions tpl/collections/sort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 0b64fae

Please sign in to comment.