var obj = { func: function (v) { return v; } };
for (let n = 0; n < 1000; n++) { const r = obj.func?.(true) ?? false }
for (let n = 0; n < 1000; n++) { const r = obj.func2?.(true) ?? false }
for (let n = 0; n < 1000; n++) { const r = typeof obj.func === 'function' ? obj.func(true) : false }
for (let n = 0; n < 1000; n++) { const r = typeof obj.func2 === 'function' ? obj.func2(true) : false }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
optional chain prop found | |
optional chain prop not found | |
typeof match | |
typeof mismatch |
Test name | Executions per second |
---|---|
optional chain prop found | 27315.6 Ops/sec |
optional chain prop not found | 27556.6 Ops/sec |
typeof match | 13632.3 Ops/sec |
typeof mismatch | 27603.3 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of two approaches: using optional chaining (?.
) versus checking if a value is a function using typeof
.
Optional Chaining (?.
)
Optional chaining allows you to access nested properties of an object without explicitly checking if the property exists. In this case, the code uses ?.
to call the func
method on the obj
object with the argument true
, and then checks if the result is truthy using the nullish coalescing operator (??
). If the expression is falsy, it returns false
.
Checking for Functionality using typeof
The other approach uses typeof
to check if the func2
property of the obj
object is a function. If it is, then it calls the function with the argument true
. This approach requires an explicit check for function
type before calling the method.
Pros and Cons of Each Approach
?.
):typeof
:Library Usage
There is no library used in this benchmark. The code relies on built-in JavaScript features such as optional chaining (?.
) and typeof
.
Special JS Feature or Syntax
The benchmark uses a feature that was introduced in ECMAScript 2020: the nullish coalescing operator (??
). This operator returns its first operand if it's not null or undefined, otherwise it returns its second operand.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
in
operator to check for property existence instead of optional chaining.isFunction
function from a library like Lodash.Keep in mind that these alternatives may have different performance characteristics and trade-offs, so it's essential to test them thoroughly before making a decision.