Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Last active October 8, 2017 20:47
Show Gist options
  • Save lahmatiy/ea25d0e623d88ca9848384b5707d52d9 to your computer and use it in GitHub Desktop.
Save lahmatiy/ea25d0e623d88ca9848384b5707d52d9 to your computer and use it in GitHub Desktop.
JS perf quiz

Similar solutions with very different execution times. What's the reason? Why solution #1 is too slow?

Hint: access to .length property and to variables is not an issue.

Based on a real case in CSSTree

Node v6.11.3

N Solution #1 Solution #2
10000 107 ms 5 ms
20000 287 ms 3 ms
30000 665 ms 3 ms
40000 1183 ms 4 ms
50000 1880 ms 4 ms
60000 2793 ms 6 ms
70000 7985 ms 16 ms
80000 14322 ms 20 ms
90000 21804 ms 21 ms
100000 29559 ms 23 ms
150000 83309 ms 42 ms

Node v8.6.0

N Solution #1 Solution #2
10000 98 ms 6 ms
20000 328 ms 5 ms
30000 708 ms 4 ms
40000 1272 ms 4 ms
50000 1946 ms 4 ms
60000 5943 ms 8 ms
70000 10793 ms 7 ms
80000 16535 ms 10 ms
90000 23096 ms 9 ms
100000 31433 ms 14 ms
150000 82313 ms 21 ms
function updatePos(buffer) {
for (; bufferPos < buffer.length; bufferPos++) {
if (buffer.charCodeAt(bufferPos) === 48) {
stubCounter++;
}
}
}
const N = 50000;
let buffer = '';
let bufferPos = 0;
let stubCounter = 0;
for (let i = 0, add; i < N; i++) {
add = '0123456789';
buffer += add;
updatePos(buffer);
}
console.log(stubCounter, buffer.length); // 50000 500000
function updatePos(str) {
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === 48) {
stubCounter++;
}
}
}
const N = 50000;
let buffer = '';
let stubCounter = 0;
for (let i = 0, add; i < N; i++) {
add = '0123456789';
updatePos(add);
buffer += add;
}
console.log(stubCounter, buffer.length); // 50000 500000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment