• I put together this implementation using a byte array without having to copy and allocate new strings.

    var buff = new Uint8Array(1024);
    
    //ascii string to byte array
    for (let i = 0; i < data.length; i++) {
          let c = ('0' + data.charCodeAt(i).toString(16)).slice(-­2);
          buff[i * 2] = c.charCodeAt(0);
          buff[i * 2 + 1] = c.charCodeAt(1);
    }
    
    //Ascii string from byte Array - Note 'apply' only works for 64 arguments
    function fromByteArray(len) {
          if (len < 64) return String.fromCharCode.apply(String, buff.slice(0,len));
          for (var result = [], i = 0; i < len; i += 64) {
                result.push(String.fromCharCode.apply(St­ring, buff.slice(i, i + 64)));
          }
          return result.join("").slice(0,len); 
    }
    
    //Hex string to byte array
    function toByteArray(data) {
          for (let i = 0; i < data.length/2; i++) {
                buff[i] = parseInt((data.substring(i*2,i*2+2)),16)­
          }
          buff.slice(0,data.length /2);
    }
    

    After running a process.memory() command before and after these changes, I can't see any significant memory savings. Should we expect any improvements in memory usage by using a byte array, or does the string append provide the best use of memory allocation?

    What improvements could we make to this implementation to improve memory allocation?

About

Avatar for Nadnerb @Nadnerb started