Skip to content

Instantly share code, notes, and snippets.

@xplato
Last active December 22, 2021 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xplato/35a5dc4769dd4d2c34615d61092c95d2 to your computer and use it in GitHub Desktop.
Save xplato/35a5dc4769dd4d2c34615d61092c95d2 to your computer and use it in GitHub Desktop.
The Fibonacci sequence in JavaScript: how my implementation is 161% faster.
// This code is the companion for my article:
// "Program performance: cleaner !== better"
// You can read it here:
// https://www.infinium.earth/article/program-performance
// How many interations each function is
// called to check the average.
const ITERATIONS = 100;
const BASE_N = 200;
const average = a => a.reduce((t, c) => t + c) / a.length;
// My implementation:
const myFib = (n) => {
let res = [];
// Using a while-loop here was ever so
// slightly slower.
// Moreover, using a ternary operator was
// slightly slower.
for (let i = 0; i < n; ++i) {
let v;
if (i > 1) {
v = res[i - 1] + res[i - 2];
} else {
v = i;
}
res.push(v);
}
return res;
}
// Their solution:
const theirFib = n => {
return Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
}
const checkAverage = (f) => {
let s1 = [];
for (let i = 0; i < ITERATIONS; ++i) {
const t0 = performance.now();
f(BASE_N);
const t1 = performance.now();
s1.push(t1 - t0);
}
return `${average(s1)} - ${f.name}`
};
console.log(checkAverage(myFib));
console.log(checkAverage(theirFib));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment