Skip to content
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
24 changes: 24 additions & 0 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,30 @@ func Benchmark_envStruct(b *testing.B) {
require.True(b, out.(bool))
}

func Benchmark_envStruct_noEnv(b *testing.B) {
type Price struct {
Value int
}
type Env struct {
Price Price
}

program, err := expr.Compile(`Price.Value > 0`)
require.NoError(b, err)

env := Env{Price: Price{Value: 1}}

var out any
b.ResetTimer()
for n := 0; n < b.N; n++ {
out, err = vm.Run(program, env)
}
b.StopTimer()

require.NoError(b, err)
require.True(b, out.(bool))
}

func Benchmark_envMap(b *testing.B) {
type Price struct {
Value int
Expand Down
29 changes: 25 additions & 4 deletions vm/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ import (
"fmt"
"math"
"reflect"
"sync"

"github.com/expr-lang/expr/internal/deref"
)

var fieldCache sync.Map

type fieldCacheKey struct {
t reflect.Type
f string
}

func Fetch(from, i any) any {
v := reflect.ValueOf(from)
if v.Kind() == reflect.Invalid {
Expand Down Expand Up @@ -63,8 +71,17 @@ func Fetch(from, i any) any {

case reflect.Struct:
fieldName := i.(string)
value := v.FieldByNameFunc(func(name string) bool {
field, _ := v.Type().FieldByName(name)
t := v.Type()
key := fieldCacheKey{
t: t,
f: fieldName,
}
if fi, ok := fieldCache.Load(key); ok {
field := fi.(*reflect.StructField)
return v.FieldByIndex(field.Index).Interface()
}
field, ok := t.FieldByNameFunc(func(name string) bool {
field, _ := t.FieldByName(name)
switch field.Tag.Get("expr") {
case "-":
return false
Expand All @@ -74,8 +91,12 @@ func Fetch(from, i any) any {
return name == fieldName
}
})
if value.IsValid() {
return value.Interface()
if ok {
value := v.FieldByIndex(field.Index)
if value.IsValid() {
fieldCache.Store(key, &field)
return value.Interface()
}
}
}
panic(fmt.Sprintf("cannot fetch %v from %T", i, from))
Expand Down
Loading