From 469dc31765e0a8bb915437346ea92e09b515a8a6 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sun, 6 Dec 2020 02:57:57 +0900 Subject: [PATCH] jsutil: Reduce allocating Uint8Array on go2cpp Updates #1426 --- internal/jsutil/buf_js.go | 14 +++++++++----- internal/jsutil/slice_js.go | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/internal/jsutil/buf_js.go b/internal/jsutil/buf_js.go index f4273db5e..a858beb3b 100644 --- a/internal/jsutil/buf_js.go +++ b/internal/jsutil/buf_js.go @@ -28,8 +28,6 @@ var isTypedArrayWritable = js.Global().Get("go2cpp").Truthy() // To avoid often allocating ArrayBuffer, reuse the buffer whenever possible. var temporaryBuffer = js.Global().Get("ArrayBuffer").New(16) -var uint8ArrayObj js.Value - func TemporaryUint8Array(byteLength int) js.Value { if bufl := temporaryBuffer.Get("byteLength").Int(); bufl < byteLength { for bufl < byteLength { @@ -37,14 +35,20 @@ func TemporaryUint8Array(byteLength int) js.Value { } temporaryBuffer = js.Global().Get("ArrayBuffer").New(bufl) } + return uint8Array(temporaryBuffer, 0, byteLength) +} + +var uint8ArrayObj js.Value + +func uint8Array(buffer js.Value, byteOffset, byteLength int) js.Value { if isTypedArrayWritable { if uint8ArrayObj.IsUndefined() { uint8ArrayObj = js.Global().Get("Uint8Array").New() } - uint8ArrayObj.Set("buffer", temporaryBuffer) - uint8ArrayObj.Set("byteOffset", 0) + uint8ArrayObj.Set("buffer", buffer) + uint8ArrayObj.Set("byteOffset", byteOffset) uint8ArrayObj.Set("byteLength", byteLength) return uint8ArrayObj } - return js.Global().Get("Uint8Array").New(temporaryBuffer, 0, byteLength) + return js.Global().Get("Uint8Array").New(buffer, byteOffset, byteLength) } diff --git a/internal/jsutil/slice_js.go b/internal/jsutil/slice_js.go index a495df15f..d4ace466c 100644 --- a/internal/jsutil/slice_js.go +++ b/internal/jsutil/slice_js.go @@ -95,7 +95,7 @@ func CopySliceToJS(dst js.Value, src interface{}) { case []uint8: js.CopyBytesToJS(dst, s) case []int8, []int16, []int32, []uint16, []uint32, []float32, []float64: - a := js.Global().Get("Uint8Array").New(dst.Get("buffer"), dst.Get("byteOffset"), dst.Get("byteLength")) + a := uint8Array(dst.Get("buffer"), dst.Get("byteOffset").Int(), dst.Get("byteLength").Int()) js.CopyBytesToJS(a, sliceToByteSlice(s)) default: panic(fmt.Sprintf("jsutil: unexpected value at CopySliceToJS: %T", s))