algorithmic complexity:
a measure of
how performance scales
with input size
Slide 26
Slide 26 text
O(1)
O(log n)
O(n)
O(n log n)
O(n2)
O(n3)
Slide 27
Slide 27 text
array[0] + array[1];
O(1) — instant
Slide 28
Slide 28 text
for (const item of array) {
sum += item;
}
O(n) — suspicious
Slide 29
Slide 29 text
O(n2) — ridiculously slow
for (let i = 0, n = array.length; i < n; i++) {
for (let j = i + 1; j < n; j++) {
sum += array[i] + array[j];
}
}
Slide 30
Slide 30 text
function foo(array) {
for (const item of array) {
array[array.indexOf(item)] = item + 10;
}
}
O(n2) — ridiculously slow
Slide 31
Slide 31 text
function foo(array) {
for (const item of array) {
bar(array, item);
}
}
function bar(array, item) {
array[array.indexOf(item)] = item + 10;
}
O(n2) — ridiculously slow
Slide 32
Slide 32 text
accidentallyquadratic.tumblr.com
Slide 33
Slide 33 text
O(n3) — rewrite from scratch
for (let i = 0, n = array.length; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
sum += array[i] + array[j];
}
}
}
Slide 34
Slide 34 text
if (j < 0) {
if (triangles.length === 0) triangles.push([i]);
return;
}
for (let n = triangles.length, a = 0; a < n; ++a) {
let sa = triangles[a];
if (sa[0] === j) {
for (let b = a + 1; b < n; ++b) {
let sb = triangles[b];
if (sb[sb.length - 1] === i) {
triangles.splice(b, 1);
triangles[a] = sa = sb.concat(sa);
return;
}
}
sa.unshift(i);
return;
}
d3/d3-delaunay#23
const lines = input.split(';');
for (const line of lines) {
const segments = line.split(',');
for (const segment of segments) {
const decoded = decode(segment);
for (const i of decoded) {
...
}
}
}
Rich-Harris/sourcemap-codec#71
Slide 41
Slide 41 text
for (let i = 0; i < input.length; i++) {
const c = input.charCodeAt(i);
if (c === 44) { // ","
...
} else if (c === 59) { // ";"
...
Rich-Harris/sourcemap-codec#71
3 times faster
established !== best
there is always room
for improvement
Slide 64
Slide 64 text
1. learn how things work under the hood
2. don’t be afraid to reinvent the wheel
3. simplify your code constantly
4. practice optimization, and you’ll learn
how to write fast code by default