Converting between strings and ArrayBuffers

后端 未结 24 875
慢半拍i
慢半拍i 2020-11-22 04:50

Is there a commonly accepted technique for efficiently converting JavaScript strings to ArrayBuffers and vice-versa? Specifically, I\'d like to be able to write the contents

24条回答
  •  既然无缘
    2020-11-22 05:30

    Blob is much slower than String.fromCharCode(null,array);

    but that fails if the array buffer gets too big. The best solution I have found is to use String.fromCharCode(null,array); and split it up into operations that won't blow the stack, but are faster than a single char at a time.

    The best solution for large array buffer is:

    function arrayBufferToString(buffer){
    
        var bufView = new Uint16Array(buffer);
        var length = bufView.length;
        var result = '';
        var addition = Math.pow(2,16)-1;
    
        for(var i = 0;i length){
                addition = length - i;
            }
            result += String.fromCharCode.apply(null, bufView.subarray(i,i+addition));
        }
    
        return result;
    
    }
    

    I found this to be about 20 times faster than using blob. It also works for large strings of over 100mb.

提交回复
热议问题