Skip to content

Instantly share code, notes, and snippets.

@tsamaya
Created March 14, 2018 10:40
Show Gist options
  • Save tsamaya/00acc10d6079d043087a44b9334c13f3 to your computer and use it in GitHub Desktop.
Save tsamaya/00acc10d6079d043087a44b9334c13f3 to your computer and use it in GitHub Desktop.
const N = 1000000;
const STR = 'abcdefghijkl';
function simpleConcat() {
let str = '';
for (let i = 0; i < N; i++) {
str += STR;
}
return str;
}
function joinConcat() {
let arr = [];
for (let i = 0; i < N; i++) {
arr.push(STR);
}
return arr.join('');
}
const M = 12;
function bufferedConcat() {
let str = '';
let buf = '';
for (let i = 0; i < N; i++) {
buf += STR;
if (buf.length >= M) {
str += buf;
buf = '';
}
}
str += buf;
return str;
}
// warmup
let str1 = simpleConcat();
let str2 = joinConcat();
let str3 = bufferedConcat();
if (str3 !== str1) throw new Error('Bad buffered concat.');
console.time('+=');
for (let i = 0; i < 10; i++) str1 = simpleConcat();
console.timeEnd('+=');
console.time('push/join');
for (let i = 0; i < 10; i++) str2 = joinConcat();
console.timeEnd('push/join');
console.time('buffered +=');
for (let i = 0; i < 10; i++) str3 = bufferedConcat();
console.timeEnd('buffered +=');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment