Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>Get most performant function

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

Discover More Reads

Real Stories & Real Success

Do you have a tech idea?

Let’s talk!

By submitting this form, you agree with JetRockets’ Privacy Policy

If you prefer email, write to us at hello@jetrockets.com