What is the memory usage in javascript when using the comparators such as '==', '===' and Object.is() method?

78 Views Asked by At

==, ===, Object.is(value1, value2) are used in JavaScript to compare values. This will return true or false. I want to know if there is any memory usage difference between these comparators.

example usages, if (value1 == value2) {}

if (value1 === value2) {}

if (Object.is(value1, value2) {}

Went through the documentation.

2

There are 2 best solutions below

0
NullDev On

This isn't that easy to answer because that's entirely implementation dependent. This kind of "under-the-hood behavior" isn't specified/standardized by ECMA so you'd have to benchmark some JavaScript engines individually.

Lets take V8 for example: If you compare the same types, both == and === use the exact same algorithm. In theory == should always be slower than === because "equals" actually calls "strict equals" internally. But the memory usage difference is so small that you can't even accurately benchmark it, given that other factors are involved as well.

But then again, it entirely depends on the implementation and I'd say the actual differences in terms of memory usage are completely insignificant.

So to actually answer your question:

I want to know if there is any memory usage difference between these comparators.

There will always be some difference, but it's nothing you'll ever notice.

0
traktor On

The operators are executed by the JavaScript engine during the course of evaluating an expression. The code to do likely written in a lower level language than JS and make use of the run time stack. But when evaluated there will only be the result of the comparison left using memory.

Intermediate results in an expression are likely to be pushed onto a computational stack at least temporarily. Depending on the engine, a boolean result might occupy up to 64 bits, maybe, depending on how the engine stores primitive values.

Specification of the steps evaluation of operators must go through, including or excluding automatic type conversions, can be found in the ECMAScript Standard. Be aware these are notional steps and may not represent the order or take into account all of the optimizations performed by an actual script engine.

Be wary of assuming that choice of one operator over another, or the sequence of operators might lead to massive performance gains. Evaluation of the operator may only be a small part of what the JavaScript compiler asks the run time engine to do, and in some cases may depend on the type of operands supplied to an operator.