Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More reduced allocations #7193

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions ast/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"sort"
"strings"
"sync"

"github.com/open-policy-agent/opa/util"
)
Expand Down Expand Up @@ -137,8 +138,15 @@ func (i *baseDocEqIndex) Build(rules []*Rule) bool {
}

func (i *baseDocEqIndex) Lookup(resolver ValueResolver) (*IndexResult, error) {
tr := ttrPool.Get().(*trieTraversalResult)

tr := newTrieTraversalResult()
defer func() {
clear(tr.unordered)
tr.ordering = tr.ordering[:0]
tr.values.clear()

ttrPool.Put(tr)
}()

err := i.root.Traverse(resolver, tr)
if err != nil {
Expand Down Expand Up @@ -419,13 +427,22 @@ type trieWalker interface {
type trieTraversalResult struct {
unordered map[int][]*ruleNode
ordering []int
values Set
values *set
}

var ttrPool = sync.Pool{
New: func() any {
return newTrieTraversalResult()
},
}

func newTrieTraversalResult() *trieTraversalResult {
return &trieTraversalResult{
unordered: map[int][]*ruleNode{},
values: NewSet(),
// Number 3 is arbitrary, but seemed to be the most common number of values
// stored when benchmarking the trie traversal against a large policy library
// (Regal).
values: newset(3),
}
}

Expand All @@ -439,7 +456,7 @@ func (tr *trieTraversalResult) Add(t *trieNode) {
tr.unordered[root] = append(nodes, node)
}
if t.values != nil {
t.values.Foreach(tr.values.Add)
t.values.Foreach(tr.values.insertNoGuard)
}
}

Expand Down
Loading
Loading