TextEncoder vs String hash v2

Test TextEncoder encoding vs simply encoding with a string
9 months ago
User agent: Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0
Test name Executions per second
Baseline encoder 8036.6 Ops/sec
baseline hash 11038.6 Ops/sec
Script Preparation code:
AخA
 
iterations = 1000;
function randomStringGen(n) {
    let strings = [];
    for (let i = 0; i < n; i++) {
      let s = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
      strings[i] = s;
    }
    return strings;
}
var randomStrings = randomStringGen(iterations);
var encoder = new TextEncoder();
var arrayBuffer = new ArrayBuffer(iterations*1000);
var buffer = new Uint8Array(arrayBuffer);
Tests:
  • Baseline encoder

     
    var j = 0;
    for (let i = 0; i < iterations; i++) {
      var str = randomStrings[i % iterations];
      buffer[j] = str.length;
      var res = encoder.encodeInto(str, buffer.subarray(j+1));
      j = j + res.written;
    }
  • baseline hash

     
    var stringMap = {};
    var counter = 0;
    function stringToMap(s) {
        var i = stringMap[s];
        if (i === undefined) {
          stringMap[s] = counter++;
        } else {
          return i;
        }
    }
    var j = 0;
    for (let i = 0; i < iterations; i++) {
      var str = randomStrings[i % iterations];
      var num = stringToMap(str);
      buffer[j] = num;
      j = j + 8;
    }
Open this result on MeasureThat.net