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 +='); |
+=
is only slower when N = 1000000!
+=: 2503.689ms
push/join: 1331.478ms
buffered +=: 627.932ms
+= x 4.27 ops/sec ±14.43% (15 runs sampled)
push(/join x 8.28 ops/sec ±11.51% (25 runs sampled)
buffered x 13.65 ops/sec ±14.12% (28 runs sampled)
lowering N to a more realistic 1000, changes the results to following on node 10.2.1
+=: 0.650ms
push/join: 8.361ms
buffered +=: 2.534ms
+= x 53,101 ops/sec ±2.03% (76 runs sampled)
push(/join x 17,733 ops/sec ±2.72% (80 runs sampled)
buffered x 32,264 ops/sec ±1.47% (81 runs sampled)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting, I guess this is the answer: https://softwareengineering.stackexchange.com/a/90231