var nullValue = null;
var undefinedValue;
var trueValue = true;
(nullValue ?? undefinedValue ?? trueValue);
(nullValue || undefinedValue || trueValue);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Nullish coalescing | |
Logical OR |
Test name | Executions per second |
---|---|
Nullish coalescing | 94514312.0 Ops/sec |
Logical OR | 101892040.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
The provided JSON represents a JavaScript microbenchmark, which is a small program designed to measure the performance of specific JavaScript features or libraries. In this case, there are two test cases: "Nullish coalescing" and "Logical OR".
Options Being Compared
In both test cases, we have three options being compared:
nullValue
undefinedValue
trueValue
The nullish coalescing test checks the performance of using the nullish coalescing operator (??
) to resolve these values. The logical OR test checks the performance of using the logical OR operator (||
).
Pros and Cons of Different Approaches
Nullish Coalescing Operator (??)
if
statements.Logical OR Operator (||
)
Other Considerations
In both test cases, we're using a simple script that assigns values to variables. The actual benchmarking comes from the way these variables are used in the expression.
For example, in the "Nullish Coalescing" test, the expression (nullValue ?? undefinedValue ?? trueValue)
will try to resolve undefinedValue
if nullValue
is not null or undefined, and then use trueValue
if undefinedValue
is also not defined. This requires a single comparison operation, which can be faster than using logical OR (||
).
In the "Logical OR" test, the expression (nullValue || undefinedValue || trueValue)
will perform three separate comparisons to determine the truthiness of each value.
Library or Special JS Feature Used
Neither of these test cases uses any specific library. However, they do utilize a modern JavaScript feature: nullish coalescing (??
).
Nullish coalescing is a relatively new operator introduced in ECMAScript 2020 (ES12). It allows you to use the nullish coalescing operator to handle null or undefined values in a more concise way.
Other Alternatives
If you're interested in testing other JavaScript features or libraries, here are some alternatives:
strict
option to the benchmark definition and use strict mode functions like with (strict) { ... }
.Keep in mind that each alternative will require modifications to the benchmark definition and test cases.