const a = function () { };
const b = function () { };
a === b;
const a = function () { };
const b = a;
a === b;
const a = {};
const b = {};
a === b;
const a = {};
const b = a;
a === b;
const a = Symbol("foo");
const b = Symbol("bar");
a === b;
const a = Symbol("foo");
const b = a;
a === b;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
func(diff) | |
func(eq) | |
obj(diff) | |
obj(eq) | |
symbol(diff) | |
symbol(eq) |
Test name | Executions per second |
---|---|
func(diff) | 1412302464.0 Ops/sec |
func(eq) | 1415972480.0 Ops/sec |
obj(diff) | 1413015296.0 Ops/sec |
obj(eq) | 1411407488.0 Ops/sec |
symbol(diff) | 3891802.5 Ops/sec |
symbol(eq) | 7789917.0 Ops/sec |
I'll explain the benchmark in detail, covering what's being tested, the pros and cons of each approach, and other considerations.
Benchmark Overview
The provided benchmark compares the performance of three different approaches:
===
operator.What's being tested?
The benchmark measures the performance of each approach by executing the following code:
const a = function () { };;
(Function literal)const b = function () { };
(Another function literal)a === b;
(Comparing two functions)For object equality, it uses:
const a = {};
const b = {};
a === b;
For symbol equality, it uses:
const a = Symbol("foo");
const b = Symbol("bar");
a === b;
Function Equality (eq)
In JavaScript, when comparing two functions using ===
, the browser performs the following steps:
Function
for each function.Pros:
Cons:
Function
instances are created and compared.Object Equality (diff)
The benchmark uses a custom diff algorithm to compare two objects. The idea is to find the differences between the two objects by comparing their property names and values.
Pros:
Cons:
Symbol Equality (diff/symbol)
The benchmark uses a custom diff algorithm to compare two symbols. Symbols are unique, immutable properties of objects that cannot be reassigned.
Pros:
Cons:
Symbol Equality (eq)
For symbol equality, a simple comparison is performed:
const a = Symbol("foo");
const b = a;
In this case, a
and b
are two references to the same symbol. The benchmark compares them using their raw value (a === b
) rather than comparing them as objects.
Pros:
Cons:
Other Considerations
When running this benchmark, consider the following factors that can impact performance:
===
, JavaScript performs type coercion. This can lead to unexpected behavior if the types are not what you expect.Alternatives
If you're interested in exploring alternative approaches or optimizing your benchmark, consider the following:
Object.is()
instead of ===
for object comparison: This function is specifically designed for comparing objects and provides better performance.