let x = null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? 1;
let x = null || undefined || null || undefined || null || undefined || null || undefined || null || undefined || 1;
let x = 1 ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? 1;
let x = 1 || undefined || null || undefined || null || undefined || null || undefined || null || undefined || 1;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Nullish coalescing (??) | |
Logical OR (||) | |
Nullish coalescing (??) [short-circuit] | |
Logical OR (||) [short-circuit] |
Test name | Executions per second |
---|---|
Nullish coalescing (??) | 177495840.0 Ops/sec |
Logical OR (||) | 184905008.0 Ops/sec |
Nullish coalescing (??) [short-circuit] | 190664000.0 Ops/sec |
Logical OR (||) [short-circuit] | 183126720.0 Ops/sec |
Overview of the Benchmark
The provided benchmark compares two approaches for handling null and undefined values in JavaScript: nullish coalescing (??
) and logical OR (||
). Nullish coalescing is a newer feature introduced in ECMAScript 2020, while logical OR is an older operator.
Nullish Coalescing (??
)
Nullish coalescing is a binary operator that returns its left operand if it's not null or undefined. If the left operand is null or undefined, the right operand is returned instead.
Example benchmark definition:
let x = null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? null ?? undefined ?? 1;
Logical OR (||
)
Logical OR is a binary operator that returns its first non-false value. If both operands are false, it returns false.
Example benchmark definition:
let x = null || undefined || null || undefined || null || undefined || null || undefined || null || undefined || 1;
Comparison and Trade-Offs
The comparison between ??
and ||
is mainly focused on their behavior when dealing with consecutive null or undefined values.
??
)||
)Logical OR (||
) [short-circuit]
Pros:
Cons:
??
, as it only short-circuits after evaluating the entire sequenceLibrary and Special JS Features
The benchmark definition provided uses no external libraries. It's solely focused on demonstrating the comparison between two built-in JavaScript operators.
There are no special JavaScript features being tested or compared in this specific benchmark. However, if we were to expand the scope of the benchmark, we could explore other comparisons involving different features like ==
/===
, ===
with object equality checks, or even more advanced topics like try-catch
performance.
Alternatives and Variations
If you want to explore similar benchmarks or alternatives, consider the following:
==
, ===
, !==
) or arithmetic operators (+
, -
, *
)