Skip to content

Instantly share code, notes, and snippets.

@tarunKoyalwar
Created August 10, 2023 18:27
Show Gist options
  • Save tarunKoyalwar/e0f3a712c599f4bd0e8ee2fcd4c4dc02 to your computer and use it in GitHub Desktop.
Save tarunKoyalwar/e0f3a712c599f4bd0e8ee2fcd4c4dc02 to your computer and use it in GitHub Desktop.
benchmarking function usage in govaluate and goja
package benchmarks
import (
"encoding/base64"
"fmt"
"testing"
"github.com/Knetic/govaluate"
"github.com/dop251/goja"
"github.com/stretchr/testify/require"
)
func BenchmarkGoValuateNCompile(b *testing.B) {
base64Func := func(args ...interface{}) (interface{}, error) {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprint(args[0]))), nil
}
funcMap := map[string]govaluate.ExpressionFunction{
"base64": base64Func,
}
for i := 0; i < b.N; i++ {
compiled, err := govaluate.NewEvaluableExpressionWithFunctions(`base64("test@scanme.sh")`, funcMap)
require.Nil(b, err)
_, _ = compiled.Evaluate(map[string]interface{}{})
}
}
func BenchmarkGojaWithCompile(b *testing.B) {
vm := goja.New()
b64Func := func(call goja.FunctionCall) goja.Value {
res := base64.StdEncoding.EncodeToString([]byte(call.Argument(0).String()))
return vm.ToValue(res)
}
vm.Set("base64", b64Func)
script := `base64("test@scanme.sh")`
for i := 0; i < b.N; i++ {
_, err := vm.RunString(script)
require.Nil(b, err)
}
}
@tarunKoyalwar
Copy link
Author

Result

go test -bench=. -benchtime=10s -benchmem
goos: darwin
goarch: arm64
pkg: github.com/tarunKoyalwar/benchMarks
BenchmarkGoValuateNCompile-8   	 3675090	      3274 ns/op	    2760 B/op	      73 allocs/op
BenchmarkGojaWithCompile-8     	 6726903	      1789 ns/op	    1560 B/op	      35 allocs/op
PASS
ok  	github.com/tarunKoyalwar/benchMarks	29.551s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment