var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
obj["f"] === undefined
!("f" in obj)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
undefined | |
in |
Test name | Executions per second |
---|---|
undefined | 11385044.0 Ops/sec |
in | 29604638.0 Ops/sec |
I'd be happy to help explain the JavaScript microbenchmark on MeasureThat.net.
What is being tested?
The benchmark is testing two different approaches to check if a property ("f"
in this case) exists or not in an object (obj
).
obj[\"f\"] === undefined
: This approach checks if the property "f"
exists in the object by attempting to access it using bracket notation. If the property does exist, obj["f"]
will be a valid value (e.g., an empty string or null), and the comparison with undefined
will return false
. However, if the property does not exist, obj["f"]
will be undefined
, and the comparison will return true
.!(\"f\" in obj)
: This approach uses the "in" operator to check if the property "f"
exists in the object. The "in" operator returns a boolean value indicating whether the property is present or not.Pros and Cons of each approach:
obj[\"f\"] === undefined
:obj["f"]
is not a valid value).!(\"f\" in obj)
:Library and special features:
There are no libraries mentioned in this benchmark. However, it's worth noting that some JavaScript engines may have additional optimizations or behavior when using the "in" operator or bracket notation. For example, modern browsers use the Map
API to implement the "in" operator, which can lead to performance differences.
No special features are used in this benchmark, such as async/await, generators, or destructuring.
Other alternatives:
For checking if a property exists in an object, other approaches could include:
Object.prototype.hasOwnProperty.call()
method (e.g., obj.hasOwnProperty("f")
).WeakMap
API to store and query objects (e.g., new WeakMap().has(obj, "f")
).?.
) or the nullish coalescing operator (??
) in a more creative way.However, these alternatives may not be as straightforward or readable as the original approaches, and may require additional explanation to developers unfamiliar with them.