Monday, 10 September 2018

How to measure performance of a function in JS? When performance.now() shows strange behaviour

As seen in below code when I increase the size of the string it leads to a 0 mili seconds difference. And moreover there is an inconsistency as the string count goes on increasing.

Am I doing some thing wrong here.

let stringIn = document.getElementById('str');
let button = document.querySelector('button');

button.addEventListener('click', () => {
  let t1 = performance.now();
  functionToTest(stringIn.value);
  let t2 = performance.now();
  console.log(`time taken is ${t2 - t1}`);
});

function functionToTest(str) {
  let total = 0;
  for(i of str) {
   total ++;
  }
  return total;
}
<input id="str">
<button type="button">Test string</button>

I tried using await too but same result with below code as well. The function enclosing the below code is async.

let stringArr = this.inputString.split(' ');
let longest = '';
const t1 = performance.now();
let length = await new Promise(resolve => {
  stringArr.map((item, i) => {
    longest = longest.length < item.length ? longest : item;
    i === stringArr.length - 1 ? resolve(longest) : '';
  });
});
const diff = performance.now() - t1;
console.log(diff);
this.result = `The time taken in mili seconds is ${diff}`;

I've tried this answer as well but it is also inconsistent.

As a workaround I tried using console.time feature but It doesn't allow the time to be rendered and isn't accurate as well



from How to measure performance of a function in JS? When performance.now() shows strange behaviour

No comments:

Post a Comment