Why is the strict equality operator slightly slower than the equality operator in javascript?

Why is the strict equality operator slightly slower than the equality operator in javascript?

As I have read from the accepted answer Read more, strict equality comparison should be slightly faster than normal equality, as it doesn't involve type coercion, quote

Strict comparison (===) will always be slightly faster, but the difference is usually negligible

However, when I tried to benchmark this in-browser, the result seems to suggest otherwise

I tried the following code, which runs both types of equality on the same two strings ("123456") for 10000 times and benchmarks their execution time.

console.time("test");for(i=0;i<10000;i++)if("123456"==="123456")continue;console.timeEnd("test");
console.time("test2");for(i=0;i<10000;i++)if("123456"=="123456")continue;console.timeEnd("test2");

I got:

test: 0.342041015625 ms
test2: 0.26318359375 ms

which suggests that normal equality should be faster than strict equality in the context of strings. Benchmarking on numbers shows similar results

console.time("test");for(i=0;i<10000;i++)if(123456===123456)continue;console.timeEnd("test");
console.time("test2");for(i=0;i<10000;i++)if(123456==123456)continue;console.timeEnd("test2");

output:

test: 0.4560546875 ms
test2: 0.316162109375 ms

why?

Answer

Because of JavaScript engine optimizations, especially in V8:

When both operands are known constants (like two literals), the engine can apply constant folding and dead code elimination, making both == and === extremely fast — sometimes even optimized away entirely.

The loose equality == skips the type check when both operands are already the same type, which can make it marginally faster than === in tight loops involving primitives.

However, the difference is negligible and only shows up in artificial micro-benchmarks.

In real-world usage, === is just as fast or faster, and should always be preferred unless coercion is explicitly needed.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles