Usage
function sum(array: number[]): number {
let result = 0;
for (let i = 0; i < array.length; i++) {
result += array[i];
}
return result;
}
const input = Array(1000).fill(0).map((_, i) => i);
const result = experiment({
label: 'sum refactoring',
use: () => sum(input),
try: () => input.reduce((acc, val) => acc + val)
});
// result === sum(input)
Console output
[Experiment] sum refactoring
❌ -23% slower
use ⏱️ 0.06499991286545992ms
try ⏱️ 0.05000003147870302ms
diff ⏱️ -0.014999881386756897ms
✔️ strict equality
✔️ 499500 === 499500
✔️ 499500 == 499500
✔️ 499500 === 499500 (via JSON.stringify)
This function is inspired by GitHub's Scientist!.
Please note that it's better to check your refactorings with unit tests.