DEV Community

Cover image for Always and everywhere make Triple equals
Vladimir Schneider
Vladimir Schneider

Posted on

Always and everywhere make Triple equals

Hi there 👋🏼

Today I realized that a triple equal does an additional check to compare types of operands.

I got excited at the moment and I go to write a benchmark to check it!

I wrote two funny and stupid functions for it

With double equal

const f1 = () => {
  const v = Math.random();
  if (v === '2') {
    return true;
  }
  return false;
};
Enter fullscreen mode Exit fullscreen mode

And with triple equal

const f2 = () => {
  const v = Math.random();
  if (v == '2') {
    return true;
  }
  return false;
};
Enter fullscreen mode Exit fullscreen mode

And after that, I run a benchmark and saw what I did not expect.

Average f1 is faster than f2 for 80%. WHAT?!

I rewrote functions and in equal replaced string '2' to number 2 and did run a benchmark again.

So that I saw that functions execution times do not have a lot of difference.

So. What conclusion can I do?

Javascript engine spends a lot of time on type conversion, but using triple equal does not do your code very slowly.

Thank you!

Top comments (1)

Collapse
 
kasandrop profile image
kasandrop

I would suggest the author of the article to read it as well.