From b297eb65a33c6e3b45f6434652030df21d7f88c0 Mon Sep 17 00:00:00 2001 From: Teemu Koponen Date: Tue, 18 Feb 2020 10:16:53 -0800 Subject: [PATCH] Remove unnecessary heap allocations and calls to C. Instead of allocating the function name and function parameter/return value holders for each function invocation, pre-allocate them. This is possible because invocations occur sequentially (in presence of no threading). This both reduces GC pressure and removes two cgo calls. --- wasmer/instance.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/wasmer/instance.go b/wasmer/instance.go index 147a9d4d..d5f47933 100644 --- a/wasmer/instance.go +++ b/wasmer/instance.go @@ -210,6 +210,21 @@ func getExportsFromInstance( var numberOfExpectedArguments = int(wasmFunctionInputsArity) + var wasmInputs = make([]cWasmerValueT, wasmFunctionInputsArity) + var wasmOutputs = make([]cWasmerValueT, wasmFunctionOutputsArity) + + type wasmFunctionNameHolder struct { + CPointer *cChar + } + + wasmFunctionName := &wasmFunctionNameHolder{ + CPointer: cCString(exportedFunctionName), + } + + runtime.SetFinalizer(wasmFunctionName, func(h *wasmFunctionNameHolder) { + cFree(unsafe.Pointer(h.CPointer)) + }) + exports[exportedFunctionName] = func(arguments ...interface{}) (Value, error) { var numberOfGivenArguments = len(arguments) var diff = numberOfExpectedArguments - numberOfGivenArguments @@ -220,8 +235,6 @@ func getExportsFromInstance( return I32(0), NewExportedFunctionError(exportedFunctionName, fmt.Sprintf("Given %d extra argument(s) when calling the `%%s` exported function; Expect %d argument(s), given %d.", -diff, numberOfExpectedArguments, numberOfGivenArguments)) } - var wasmInputs = make([]cWasmerValueT, wasmFunctionInputsArity) - for nth, value := range arguments { var wasmInputType = wasmFunctionInputSignatures[nth] @@ -333,11 +346,6 @@ func getExportsFromInstance( } } - var wasmOutputs = make([]cWasmerValueT, wasmFunctionOutputsArity) - - var wasmFunctionName = cCString(exportedFunctionName) - defer cFree(unsafe.Pointer(wasmFunctionName)) - var wasmInputsCPointer *cWasmerValueT if wasmFunctionInputsArity > 0 { @@ -356,7 +364,7 @@ func getExportsFromInstance( var callResult = cWasmerInstanceCall( instance, - wasmFunctionName, + wasmFunctionName.CPointer, wasmInputsCPointer, wasmFunctionInputsArity, wasmOutputsCPointer,