Converting between strings and ArrayBuffers

后端 未结 24 908
慢半拍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:14

    After playing with mangini's solution for converting from ArrayBuffer to String - ab2str (which is the most elegant and useful one I have found - thanks!), I had some issues when handling large arrays. More specefivally, calling String.fromCharCode.apply(null, new Uint16Array(buf)); throws an error:

    arguments array passed to Function.prototype.apply is too large.

    In order to solve it (bypass) I have decided to handle the input ArrayBuffer in chunks. So the modified solution is:

    function ab2str(buf) {
       var str = "";
       var ab = new Uint16Array(buf);
       var abLen = ab.length;
       var CHUNK_SIZE = Math.pow(2, 16);
       var offset, len, subab;
       for (offset = 0; offset < abLen; offset += CHUNK_SIZE) {
          len = Math.min(CHUNK_SIZE, abLen-offset);
          subab = ab.subarray(offset, offset+len);
          str += String.fromCharCode.apply(null, subab);
       }
       return str;
    }
    

    The chunk size is set to 2^16 because this was the size I have found to work in my development landscape. Setting a higher value caused the same error to reoccur. It can be altered by setting the CHUNK_SIZE variable to a different value. It is important to have an even number.

    Note on performance - I did not make any performance tests for this solution. However, since it is based on the previous solution, and can handle large arrays, I see no reason why not to use it.

提交回复
热议问题