JSFiddle - React, Tailwind, and code Playground
HTML
See developer console for results.
JavaScript
let iterations = 500000,
string = "These are strange characters... \xFF\uFFFF\u0FFF\u01FF and more of them coming \u1111\u2222\u3333\u4444\u5555\u6666\u7777\u8888\u9999";
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function encode_fixed_length(s) {
let length = s.length << 1,
bytes = new Array(length),
fromCharCode = String.fromCharCode;
for (let i = 0; i < length; i += 2) {
let code = s.charCodeAt(i >> 1);
bytes[i] = fromCharCode((code & 0xFF00) >> 8);
bytes[i + 1] = fromCharCode(code & 0x00FF);
}
return bytes.join('');
}
function decode_fixed_length(s) {
let length = s.length,
chars = new Array(length >> 1);
for (let i = 0; i < length; i += 2) {
chars[i >> 1] =
String.fromCharCode((s.charCodeAt(i) << 8) + s.charCodeAt(i + 1));
}
return chars.join('');
}
console.log(decode_fixed_length(encode_fixed_length("hi")));
console.time('utf8');
for (let i = 0; i < iterations; ++i) {
var result = encode_utf8(string);
}
console.timeEnd('utf8');
console.time('fixed_length');
for (let i = 0; i < iterations; ++i) {
var result = encode_fixed_length(string);
}
console.timeEnd('fixed_length');