Run details:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36
Chrome 86
Linux
Desktop
4 years ago
Test name Executions per second
String.fromCharCode.apply 1216.1 Ops/sec
String.fromCharCode 45.2 Ops/sec
bytesToBase64 82.7 Ops/sec
arr join 41.4 Ops/sec
byteArrayToString 1396.9 Ops/sec
Script Preparation code:
x
 
var ab = new ArrayBuffer(70*1024);
var uint8 = new Uint8Array(ab);
for (var i = 0; i < ab.byteLength; i++) {
    uint8[i] = i % 256;
}
var expected = window.btoa(String.fromCharCode.apply(null, uint8));
function byteArrayToString(bytes) {
  var CHUNK_SIZE = 8*1024;
  if (bytes.length <= CHUNK_SIZE)
    return String.fromCharCode.apply(null, bytes);
  var str = '';
  for (var i = 0; i < bytes.length; i += CHUNK_SIZE)
    str += String.fromCharCode.apply(null, bytes.slice(i, i+CHUNK_SIZE));
  return str;
}
function validate(res){
  if (res !== expected)
      throw "expected=" + expected + " but got " + res;
}
function uint6ToB64(nUint6) {
  return nUint6 < 26 ?
      nUint6 + 65
    : nUint6 < 52 ?
      nUint6 + 71
    : nUint6 < 62 ?
      nUint6 - 4
    : nUint6 === 62 ?
      43
    : nUint6 === 63 ?
      47
    :
      65;
};
function bytesToBase64(aBytes) {
  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";
  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
    nMod3 = nIdx % 3;
    nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
      nUint24 = 0;
    }
  }
  return  eqLen === 0 ?
            sB64Enc
          :
            sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
};
Tests:
  • String.fromCharCode.apply

     
    var bin = String.fromCharCode.apply(null, uint8);
    var res = window.btoa(bin)
    validate(res)
  • String.fromCharCode

     
    var bin = '';
    for (var i = 0; i < uint8.byteLength; i++)
      bin += String.fromCharCode(uint8[i]);
    var res = window.btoa(bin)
    validate(res)
  • bytesToBase64

     
    var res = bytesToBase64(uint8)
    validate(res)
  • arr join

     
    var bin = [];
    for (var i = 0; i < uint8.byteLength; i++)
      bin.push(String.fromCharCode(uint8[i]));
    var res = window.btoa(bin.join(''))
    validate(res)
  • byteArrayToString

     
    var bin = byteArrayToString(uint8);
    var res = window.btoa(bin)
    validate(res)