Get most performant function
Let's say you need to determine which function is execute faster.
Write a function that take array of functions and iterates each of them a certain number of times.
Will use the difference in performance.now() values before and after to get the total time in milliseconds each iteration running.
Play with iterations argument to get more or less reliable results.
const mostPerformantFunction = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
console.log(times);
return times.indexOf(Math.min(...times));
};
mostPerformantFunction([
() => {
[1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
},
() => {
[1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
}
]); // 1