var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
undefined !== obj.d;
'undefined' !== typeof obj.d;
'd' in obj;
obj.hasOwnProperty( 'd' );
!! obj.d;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
undefined | |
typeof | |
in | |
hasOwnProperty | |
bool |
Test name | Executions per second |
---|---|
undefined | 324323616.0 Ops/sec |
typeof | 718730432.0 Ops/sec |
in | 717454208.0 Ops/sec |
hasOwnProperty | 104045064.0 Ops/sec |
bool | 715997568.0 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of different JavaScript operators for object lookup: undefined
, typeof
, in
, hasOwnProperty
, and a boolean test (!! obj.d;
).
Operator Comparison
Here's an explanation of each operator, their pros and cons, and alternative approaches:
undefined !== obj.d;
)obj.d
has been assigned a value (i.e., is not undefined
). It's often used to avoid errors when accessing object properties.?.
) introduced in ECMAScript 2020, which allows safe navigation of nested objects without throwing an error. Example: obj?.d;
'undefined' !== typeof obj.d;
)obj.d
is indeed undefined
.===
operator.?.
) instead, which provides similar functionality without the need for typeof
. Example: '?' in obj;
'd' in obj;
)'d'
exists in the object obj
.hasOwnProperty
, but returns a boolean value.?.
) instead, which provides similar functionality without the need for in
. Example: obj['d'] !== undefined;
obj.hasOwnProperty( 'd' );
)'d'
exists in the object obj
and was not inherited from a parent object.in
, as it excludes inherited properties.?.
) instead, which provides similar functionality without the need for hasOwnProperty
. Example: obj['d'] !== undefined;
Library and Special JS Features
The benchmark uses no external libraries or special JavaScript features. The only notable feature is the use of !! obj.d;
, which is a boolean test that evaluates to true
if obj.d
has any truthy value (e.g., number, string, object). This test is not specific to any particular library or syntax.
Other Alternatives
Some alternative approaches for object lookup can be found in other languages:
.get()
method: obj.get('d', None)
instanceof
operator: obj instanceof Object && obj instanceof MyObject
Keep in mind that these alternatives may have different performance characteristics and are not directly equivalent to the JavaScript operators being tested.
Benchmark Conclusion
The benchmark provides a good overview of the performance differences between various object lookup methods in JavaScript. However, it's essential to note that the results may vary depending on specific use cases, object structures, and browser implementations.