Skip to content

Instantly share code, notes, and snippets.

@MaxGraey
Created May 17, 2020 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxGraey/6db5c6c6d7e4a0f45154b73a5e130976 to your computer and use it in GitHub Desktop.
Save MaxGraey/6db5c6c6d7e4a0f45154b73a5e130976 to your computer and use it in GitHub Desktop.
getStringImpl join array of strings vs string concat
let buffer;
const LENGTH = 1024 * 4 + 17;
const WARMUP_COUNT = 8;
function createStringBuffer(len = LENGTH) {
buffer = new ArrayBuffer(len * 2);
const U16 = new Uint16Array(buffer);
const alphabet = 'A BCDE, FGHI JKLM.; (NOPQ- RSTU, VWXYZ. abcd; efgh,) ijkl mnop. qrst- uvwxy,( z0123 4567, 89.)';
for (var i = 0; i < len; i++) {
U16[i] = alphabet.charCodeAt(Math.floor(Math.random() * alphabet.length));
}
}
const CHUNKSIZE = 1024;
function getStringImpl_orig(buffer, ptr = 0, length = LENGTH) {
// const U32 = new Uint32Array(buffer);
const U16 = new Uint16Array(buffer);
let offset = ptr >>> 1;
if (length <= CHUNKSIZE) return String.fromCharCode.apply(String, U16.subarray(offset, offset + length));
const parts = [];
do {
const last = U16[offset + CHUNKSIZE - 1];
const size = last >= 0xD800 && last < 0xDC00 ? CHUNKSIZE - 1 : CHUNKSIZE;
parts.push(String.fromCharCode.apply(String, U16.subarray(offset, offset += size)));
length -= size;
} while (length > CHUNKSIZE);
return parts.join("") + String.fromCharCode.apply(String, U16.subarray(offset, offset + length));
}
function getStringImpl_new(buffer, ptr = 0, length = LENGTH) {
// const U32 = new Uint32Array(buffer);
const U16 = new Uint16Array(buffer);
let offset = ptr >>> 1;
if (length <= CHUNKSIZE) return String.fromCharCode.apply(String, U16.subarray(offset, offset + length));
let parts = '';
do {
const last = U16[offset + CHUNKSIZE - 1];
const size = last >= 0xD800 && last < 0xDC00 ? CHUNKSIZE - 1 : CHUNKSIZE;
parts += String.fromCharCode.apply(String, U16.subarray(offset, offset += size));
length -= size;
} while (length > CHUNKSIZE);
return parts + String.fromCharCode.apply(String, U16.subarray(offset, offset + length));
}
createStringBuffer();
// warmup
for (let i = 0; i < WARMUP_COUNT; i++) {
getStringImpl_orig(buffer);
}
console.time('getStringImpl (array join)');
getStringImpl_orig(buffer);
console.timeEnd('getStringImpl (array join)');
for (let i = 0; i < WARMUP_COUNT; i++) {
getStringImpl_new(buffer);
}
console.time('getStringImpl (string concat)');
getStringImpl_new(buffer);
console.timeEnd('getStringImpl (string concat)');
@MaxGraey
Copy link
Author

Results for node.js 14.2.0:

getStringImpl (array join):    0.109ms
getStringImpl (string concat): 0.03ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment