mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-12 19:32:48 -06:00
acb606b91c
I was meant to do slides for a talk, but here we are. Fun exercise in "writing" a string without actually writing one, but rather by trying to exclude all other possible built-in function names to compare against ref as early as possible in order to make the operation inexpensive. And it worked! Down from a few allocations (worst case) and at least 3 digit ns/op, to no allocations and lower end of the 2 digit ns/op scale. For reference, this PR accounts for 700K allocations gone in `regal lint bunde`, as we do millions of builtin function calls as part of that benchmark. Another 300K+ allocs gone by revisiting the `canSkipBctx` field on the AST builtin struct, and making it public sp that client like Regal may benefit. And we did :) Signed-off-by: Anders Eknert <anders@eknert.com>
62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package ast_test
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/open-policy-agent/opa/v1/ast"
|
|
)
|
|
|
|
func TestFromBuiltinNames(t *testing.T) {
|
|
for _, name := range []string{"io.jwt.decode", "http.send", "net.cidr_contains"} {
|
|
if s, ok := ast.BuiltinNameFromRef(ast.MustParseRef(name)); !ok {
|
|
t.Fatalf("Expected to find match for %v", name)
|
|
} else if s != name {
|
|
t.Fatalf("Expected %v but got: %v", name, s)
|
|
}
|
|
}
|
|
}
|
|
|
|
func BenchmarkFromBuiltinNames(b *testing.B) {
|
|
tests := []struct {
|
|
name string
|
|
ref ast.Ref
|
|
ok bool
|
|
}{
|
|
{
|
|
name: "single part",
|
|
ref: ast.Ref{ast.VarTerm("count")},
|
|
ok: true,
|
|
},
|
|
{
|
|
name: "two parts",
|
|
ref: ast.MustParseRef("http.send"),
|
|
ok: true,
|
|
},
|
|
{
|
|
name: "three parts",
|
|
ref: ast.MustParseRef("io.jwt.decode"),
|
|
ok: true,
|
|
},
|
|
{
|
|
name: "no match",
|
|
ref: ast.MustParseRef("foo.bar.baz"),
|
|
ok: false,
|
|
},
|
|
{
|
|
name: "no match long",
|
|
ref: ast.MustParseRef("a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"),
|
|
ok: false,
|
|
},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
b.Run(tc.name, func(b *testing.B) {
|
|
for b.Loop() {
|
|
if _, ok := ast.BuiltinNameFromRef(tc.ref); ok != tc.ok {
|
|
b.Fatalf("Expected ok=%v but got: %v", tc.ok, ok)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|