首页 > 解决方案 > 获取 ArrayBuffer 的视图而不是复制

问题描述

我想做相当于ArrayBuffer.slice不实际复制内容的操作。用例是将一个非常大 (50mb) 的 ArrayBuffer 转换为字符串

下面你可以看到我正在使用new Uint16Array(buffer, start, chunkSize)). 这会从 中复制值ArrayBuffer,这很慢。关于如何提高性能的任何想法?

function arrayBufferToStr(buffer: ArrayBuffer) {
    // Use chunks to not go over call stack
    // chunks of 1024 bytes * 64
    const chunkSize = 1024 * 64
    // To right before the last chunk so the last `String.fromCharCode`
    // can skip passing a byteLength argument 
    const endCondition = buffer.byteLength - (chunkSize * 2)
    let str = ""
    let start = 0

    for (start = 0; start < endCondition; start += chunkSize * 2) {
        str += String.fromCharCode.apply(null, new Uint16Array(buffer, start, chunkSize))
    }

    const view = new Uint16Array(buffer, start)
    buffer = null
    str += String.fromCharCode.apply(null, view)


    return str
}

标签: javascriptperformancearraybuffer

解决方案


推荐阅读