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

vm: Add basic support for VM instances to be reused (via Reset()) #59

Closed
wants to merge 1 commit into from
Closed
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
45 changes: 45 additions & 0 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,48 @@ func Benchmark_largeNestedArrayAccess(b *testing.B) {
b.Fatal(err)
}
}

func Benchmark_NewVMs(b *testing.B) {
type Env struct {
Field int
}

program, err := expr.Compile(`Field > 0`, expr.Env(Env{}))
if err != nil {
b.Fatal(err)
}

env := Env{}

for n := 0; n < b.N; n++ {
_, err = vm.Run(program, &env)
}

if err != nil {
b.Fatal(err)
}
}

func Benchmark_ReuseVMs(b *testing.B) {
type Env struct {
Field int
}

program, err := expr.Compile(`Field > 0`, expr.Env(Env{}))
if err != nil {
b.Fatal(err)
}

env := Env{}

v := vm.NewVM(false)

for n := 0; n < b.N; n++ {
v.Reset()
_, err = v.RunSafe(program, &env)
}

if err != nil {
b.Fatal(err)
}
}
38 changes: 25 additions & 13 deletions vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,7 @@ import (

func Run(program *Program, env interface{}) (out interface{}, err error) {
vm := NewVM(false)

defer func() {
if r := recover(); r != nil {
h := file.Error{
Location: program.Locations[vm.pp],
Message: fmt.Sprintf("%v", r),
}
err = fmt.Errorf("%v", h.Format(program.Source))
}
}()

out = vm.Run(program, env)
return
return vm.RunSafe(program, env)
}

type VM struct {
Expand All @@ -50,6 +38,30 @@ func NewVM(debug bool) *VM {
return vm
}

func (vm *VM) RunSafe(program *Program, env interface{}) (out interface{}, err error) {
defer func() {
if r := recover(); r != nil {
h := file.Error{
Location: program.Locations[vm.pp],
Message: fmt.Sprintf("%v", r),
}
err = fmt.Errorf("%v", h.Format(program.Source))
}
}()

out = vm.Run(program, env)
return
}

func (vm *VM) Reset() {
vm.stack = vm.stack[0:0] // keep the existing memory/capacity
vm.ip = 0
vm.pp = 0
if vm.scopes != nil {
vm.scopes = vm.scopes[0:0] // keep the existing memory/capacity
}
}

func (vm *VM) Run(program *Program, env interface{}) interface{} {
vm.bytecode = program.Bytecode
vm.constants = program.Constants
Expand Down