obj = {a: 42, b:66, c: 88}
Object.prototype.hasOwnProperty.call(obj, 'b');
obj.hasOwnProperty('b');
Object.hasOwn(obj, 'b')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.prototype.hasOwnProperty | |
obj.hasOwnProperty | |
Object.hasOwn |
Test name | Executions per second |
---|---|
Object.prototype.hasOwnProperty | 74141416.0 Ops/sec |
obj.hasOwnProperty | 99637344.0 Ops/sec |
Object.hasOwn | 82719184.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided JSON represents a benchmark test that compares three different ways to check if a property exists in an object:
Object.prototype.hasOwnProperty.call(obj, 'b')
obj.hasOwnProperty('b')
Object.hasOwn(obj, 'b')
These three approaches are compared to determine which one is the fastest.
Options comparison
The three options being compared are:
Object.prototype.hasOwnProperty.call(obj, 'b')
: This method uses the hasOwnProperty()
method of the object's prototype chain and returns a boolean value indicating whether the property exists in the object or not.obj.hasOwnProperty('b')
: This method uses the hasOwnProperty()
method of the object itself (not its prototype chain) to check if the property exists.Object.hasOwn(obj, 'b')
: This method is a static method on the Object
class that checks if an object has a given property.Pros and cons
Here's a brief overview of each option:
Object.prototype.hasOwnProperty.call(obj, 'b')
hasOwnProperty()
method of the object's prototype chain, which is a standardized way to check for properties in JavaScript.hasOwnProperty()
method (option 2), since it has to traverse the prototype chain.obj.hasOwnProperty('b')
hasOwnProperty()
method, which can be faster than option 1 since it doesn't have to traverse the prototype chain.hasOwnProperty()
method in its own prototype chain.Object.hasOwn(obj, 'b')
Library and syntax
In this benchmark, no libraries are used. The syntax is standard JavaScript, with no special features or syntax.
Other considerations
When writing microbenchmarks like these, it's essential to consider factors such as:
Alternatives
If you were to write a similar benchmark, you might also consider testing other approaches, such as:
in
operator (e.g., obj['b'] in obj
)However, it's worth noting that MeasureThat.net is specifically designed to test microbenchmarks related to property existence and iteration, so the focus on hasOwnProperty()
and its variants is likely intentional.