Created
May 17, 2020 13:38
-
-
Save MaxGraey/6db5c6c6d7e4a0f45154b73a5e130976 to your computer and use it in GitHub Desktop.
getStringImpl join array of strings vs string concat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results for node.js 14.2.0: