jsutil: Reduce allocating Uint8Array on go2cpp

Updates #1426
This commit is contained in:
Hajime Hoshi 2020-12-06 02:57:57 +09:00
parent 2ca0f3f300
commit 469dc31765
2 changed files with 10 additions and 6 deletions

View File

@ -28,8 +28,6 @@ var isTypedArrayWritable = js.Global().Get("go2cpp").Truthy()
// To avoid often allocating ArrayBuffer, reuse the buffer whenever possible. // To avoid often allocating ArrayBuffer, reuse the buffer whenever possible.
var temporaryBuffer = js.Global().Get("ArrayBuffer").New(16) var temporaryBuffer = js.Global().Get("ArrayBuffer").New(16)
var uint8ArrayObj js.Value
func TemporaryUint8Array(byteLength int) js.Value { func TemporaryUint8Array(byteLength int) js.Value {
if bufl := temporaryBuffer.Get("byteLength").Int(); bufl < byteLength { if bufl := temporaryBuffer.Get("byteLength").Int(); bufl < byteLength {
for bufl < byteLength { for bufl < byteLength {
@ -37,14 +35,20 @@ func TemporaryUint8Array(byteLength int) js.Value {
} }
temporaryBuffer = js.Global().Get("ArrayBuffer").New(bufl) 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 isTypedArrayWritable {
if uint8ArrayObj.IsUndefined() { if uint8ArrayObj.IsUndefined() {
uint8ArrayObj = js.Global().Get("Uint8Array").New() uint8ArrayObj = js.Global().Get("Uint8Array").New()
} }
uint8ArrayObj.Set("buffer", temporaryBuffer) uint8ArrayObj.Set("buffer", buffer)
uint8ArrayObj.Set("byteOffset", 0) uint8ArrayObj.Set("byteOffset", byteOffset)
uint8ArrayObj.Set("byteLength", byteLength) uint8ArrayObj.Set("byteLength", byteLength)
return uint8ArrayObj return uint8ArrayObj
} }
return js.Global().Get("Uint8Array").New(temporaryBuffer, 0, byteLength) return js.Global().Get("Uint8Array").New(buffer, byteOffset, byteLength)
} }

View File

@ -95,7 +95,7 @@ func CopySliceToJS(dst js.Value, src interface{}) {
case []uint8: case []uint8:
js.CopyBytesToJS(dst, s) js.CopyBytesToJS(dst, s)
case []int8, []int16, []int32, []uint16, []uint32, []float32, []float64: 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)) js.CopyBytesToJS(a, sliceToByteSlice(s))
default: default:
panic(fmt.Sprintf("jsutil: unexpected value at CopySliceToJS: %T", s)) panic(fmt.Sprintf("jsutil: unexpected value at CopySliceToJS: %T", s))