window._x = { y: 4 };
window._z = null;
let a = typeof (_x === null || _x === void 0 ? void 0 : _x.y) === `number`;
let a = _x != null && typeof _x.y === `number`;
let a = typeof (_z === null || _z === void 0 ? void 0 : _z.y) === `number`;
let a = _z != null && typeof _z.y === `number`;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional chaining, not null | |
Explicit null check, not null | |
Optional chaining, null | |
Explicit null check, null |
Test name | Executions per second |
---|---|
Optional chaining, not null | 2379731.0 Ops/sec |
Explicit null check, not null | 3700637.8 Ops/sec |
Optional chaining, null | 6561355.0 Ops/sec |
Explicit null check, null | 6688356.0 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmark that tests the performance of two different approaches to check if an object has a certain property and its value is a specific type.
Benchmark Definition
The benchmark definition is:
let a = typeof (_x === null || _x === void 0 ? void 0 : _x.y) === `number`;
This line checks if the property y
of an object _x
exists and its value is a string that equals "number". The optional chaining operator (?.
) is used to access the y
property without throwing an error if it doesn't exist.
There are four test cases:
y
property of _x
exists and its value is a string that equals "number"._x != null
) to access the y
property.y
property of an object with null
value exists and its value is a string that equals "number"._z != null
) to access the y
property.Libraries and Special Features
There is no library used in this benchmark. However, there are some special features:
?.
) was introduced in JavaScript with the release of ECMAScript 2020 (ES2020). It allows you to access nested properties without throwing an error if a null or undefined value is encountered.void 0
expression is used to achieve null coalescing, which is also a new feature introduced in ES2020.Approach Comparison
The benchmark compares the performance of two approaches:
?.
) to access nested properties without checking for null or undefined values._x != null
or _z != null
) to ensure that the object exists before accessing its properties.Pros and Cons of Each Approach
Other Considerations
DevicePlatform
and OperatingSystem
fields are not relevant to the performance comparison but provide additional metadata about the test environment.ExecutionsPerSecond
field provides a measure of the benchmark's execution frequency, which can be used to compare the performance across different browsers or versions.Alternatives
Some possible alternatives to this benchmark could include:
??
operator (nullish coalescing) or explicit checks with in
operator.