Skip to content

Commit

Permalink
tpl/collections: Use MapRange() in Where
Browse files Browse the repository at this point in the history
Speeds up execution when the collection is a map:

```
            │ stash.bench │         fix-mapkeys.bench          │
            │   sec/op    │   sec/op     vs base               │
WhereMap-10   79.35µ ± 1%   61.45µ ± 1%  -22.56% (p=0.002 n=6)

            │ stash.bench  │          fix-mapkeys.bench          │
            │     B/op     │     B/op      vs base               │
WhereMap-10   55.36Ki ± 0%   31.35Ki ± 0%  -43.37% (p=0.002 n=6)

            │ stash.bench │         fix-mapkeys.bench         │
            │  allocs/op  │  allocs/op   vs base              │
WhereMap-10   2.003k ± 0%   2.002k ± 0%  -0.05% (p=0.002 n=6)
```
  • Loading branch information
bep committed Jan 12, 2025
1 parent 32b3978 commit a3f2978
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
8 changes: 4 additions & 4 deletions tpl/collections/where.go
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,6 @@ func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []st
for i, elemName := range path {
var err error
vvv, err = evaluateSubElem(ctxv, vvv, elemName)

if err != nil {
continue
}
Expand Down Expand Up @@ -442,9 +441,10 @@ func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []st
// checkWhereMap handles the where-matching logic when the seqv value is a Map.
func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) {
rv := reflect.MakeMap(seqv.Type())
keys := seqv.MapKeys()
for _, k := range keys {
elemv := seqv.MapIndex(k)
iter := seqv.MapRange()
for iter.Next() {
k := iter.Key()
elemv := iter.Value()
switch elemv.Kind() {
case reflect.Array, reflect.Slice:
r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op)
Expand Down
16 changes: 16 additions & 0 deletions tpl/collections/where_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -902,3 +902,19 @@ func BenchmarkWhereOps(b *testing.B) {
}
})
}

func BenchmarkWhereMap(b *testing.B) {
ns := newNs()
seq := map[string]string{}

for i := 0; i < 1000; i++ {
seq[fmt.Sprintf("key%d", i)] = "value"
}

for i := 0; i < b.N; i++ {
_, err := ns.Where(context.Background(), seq, "key", "eq", "value")
if err != nil {
b.Fatal(err)
}
}
}

0 comments on commit a3f2978

Please sign in to comment.