let a = null;
let b = 1;
const check = (a, b) => {
if (a != null) {
return a;
} else {
return b;
}
}
for (let i = 1; i < 1e6; i++){
check(a,b);
}
let a = null;
let b = 1;
const check = (a, b) => {
return a ?? b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
If/Else | |
Nullish |
Test name | Executions per second |
---|---|
If/Else | 3088.3 Ops/sec |
Nullish | 181430368.0 Ops/sec |
This benchmark compares the performance of two ways to handle potential null values in JavaScript:
1. Traditional if/else
statement:
a
is not null. If it's not null, it returns a
. Otherwise, it returns b
.2. Nullish coalescing operator (??
):
a
if it's not null or undefined; otherwise, it uses b
as the fallback value.Pros and Cons:
Nullish Coalescing:
if/else
Statement:
Other Considerations:
Real-world scenarios: In most practical applications, the performance difference between these two methods is negligible. The choice often comes down to code readability and style preferences.
Alternative libraries: There aren't any specific libraries used in this benchmark. The focus is on comparing built-in JavaScript features.
Let me know if you have any more questions about the benchmark or want to explore other JavaScript performance comparisons!