Created
March 14, 2018 10:40
-
-
Save tsamaya/00acc10d6079d043087a44b9334c13f3 to your computer and use it in GitHub Desktop.
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
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