obj = {a: 42, b:66, c: 88}
Object.prototype.hasOwnProperty.call(obj, 'b');
obj.hasOwnProperty('b');
Object.hasOwn(obj, 'b')
'b' in obj
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.prototype.hasOwnProperty | |
obj.hasOwnProperty | |
Object.hasOwn | |
in obj |
Test name | Executions per second |
---|---|
Object.prototype.hasOwnProperty | 4213763.5 Ops/sec |
obj.hasOwnProperty | 7794651.5 Ops/sec |
Object.hasOwn | 3983933.0 Ops/sec |
in obj | 8092113.5 Ops/sec |
Let's break down what is tested in the provided JSON benchmark.
Benchmark Definition:
The benchmark measures the performance of four different approaches to check if a property exists in an object:
Object.prototype.hasOwnProperty.call(obj, 'b')
obj.hasOwnProperty('b')
Object.hasOwn(obj, 'b')
'b' in obj
These approaches are tested because they have slightly different performance characteristics.
Options Compared:
The four options compared are:
hasOwnProperty
method directly on the object (obj.hasOwnProperty('b')
)hasOwnProperty
method via a call to Object.prototype.hasOwnProperty.call()
Object.hasOwn()
(introduced in ECMAScript 5)'b' in obj
Pros and Cons:
obj.hasOwnProperty('b')
: This is the most straightforward approach, as it only requires calling a single method on the object.Object.prototype.hasOwnProperty.call(obj, 'b')
: This approach uses an indirect call through Object.prototype
, which might be slower than the direct call on the object.Object.hasOwn(obj, 'b')
: This is a static method that can be called without creating an object (since Object.prototype
is still available).obj
.Object.prototype
is not available.'b' in obj
: This approach uses a property access operator (in
) to check if the object has the specified property.Library/Functionality Used:
None of these options rely on a specific library or external functionality. They are all built-in JavaScript features that can be used without additional setup.
Special JS Features/Syntax:
Object.prototype.hasOwnProperty.call()
, Object.hasOwn()
: These methods were introduced in ECMAScript 5 and provide more flexible error handling and better support for non-native objects.'b' in obj
: This syntax is a property access operator, which was introduced in ECMAScript 2008.Alternatives:
If you want to explore other approaches or alternatives, consider the following:
in
with an array: Instead of using 'a' in obj
, try using in obj
. The array will act as a key and may provide better performance due to its shorter length.for...of
loop or other iteration methods to test object property existence.Keep in mind that these alternatives might not be supported by all browsers or environments, so ensure you're testing with compatible systems before running your benchmark.