Last active
October 18, 2022 21:15
-
-
Save mourner/f88027cecea958caf8078c44c3b601bc to your computer and use it in GitHub Desktop.
A benchmark that demonstrates something is wrong with v8's concatenation performance
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; | |
function simpleConcat() { | |
let str = ''; | |
for (let i = 0; i < N; i++) { | |
str += 'a'; | |
} | |
return str; | |
} | |
function joinConcat() { | |
let arr = []; | |
for (let i = 0; i < N; i++) { | |
arr.push('a'); | |
} | |
return arr.join(''); | |
} | |
const M = 12; | |
function bufferedConcat() { | |
let str = ''; | |
let buf = ''; | |
for (let i = 0; i < N; i++) { | |
buf += 'a'; | |
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
+=
is only slower when N = 1000000!lowering N to a more realistic 1000, changes the results to following on node 10.2.1