Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Nullish coalescing V.S. if/else (native)
(version: 0)
Comparing performance of:
If/Else vs Nullish
Created:
3 years ago
by:
Guest
Jump to the latest result
Tests:
If/Else
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); }
Nullish
let a = null; let b = 1; const check = (a, b) => { return a ?? b; }
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
If/Else
Nullish
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
2 years ago
)
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
Browser/OS:
Chrome 121 on Mac OS X 10.15.7
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
If/Else
3088.3 Ops/sec
Nullish
181430368.0 Ops/sec
Autogenerated LLM Summary
(model
gemma2:9b
, generated one year ago):
This benchmark compares the performance of two ways to handle potential null values in JavaScript: **1. Traditional `if/else` statement:** - Code checks if `a` is not null. If it's not null, it returns `a`. Otherwise, it returns `b`. **2. Nullish coalescing operator (`??`)**: - This approach directly returns `a` if it's not null or undefined; otherwise, it uses `b` as the fallback value. **Pros and Cons:** * **Nullish Coalescing:** - **Pros:** More concise and readable code. - **Cons:** Can be slightly less performant in some cases due to its dynamic nature. * **`if/else` Statement:** - **Pros:** Potentially more performant in certain scenarios where the compiler can optimize it better. More familiar to developers who've been using JavaScript for a long time. - **Cons:** Can be verbose and less readable, especially when handling multiple null checks. **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!
Related benchmarks:
Nullish coalescing vs logical OR operators
Nullish coalescing V.S. Logic or operator (native)
Testing for false vs undefined vs == null vs prototype.hasOwnProperty vs hasOwn for undefined member
Nullish coalescing V.S. if (native)
Nullish coalescing vs if-chains
Comments
Confirm delete:
Do you really want to delete benchmark?