var object = {},
array = [],
i, test = 1000;
for (i = 0; i < 1000; i++) {
object['something' + i] = {};
array.push('something' + i);
}
Object.prototype.hasOwnProperty.call(object, 'something' + test)
('something' + test) in object
!!object['something' + test]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.hasOwnProperty | |
Object in | |
direct |
Test name | Executions per second |
---|---|
Object.hasOwnProperty | 2113662.0 Ops/sec |
Object in | 2768516.8 Ops/sec |
direct | 2918915.5 Ops/sec |
Let's break down what's being tested in this JavaScript microbenchmark.
The benchmark compares the performance of four different approaches to check if a property exists in an object:
Object.prototype.hasOwnProperty.call(object, 'something' + test)
: This approach uses the hasOwnProperty
method to check if the object has a property with the given name. It's a standard way to check for property existence and is widely supported.('something' + test) in object
: This approach uses the in
operator to check if the property exists in the object. The in
operator returns a boolean value indicating whether the property is present in the object or not.!!object['something' + test]
: This approach uses a simple coercion to attempt to access the property. If the property exists, the expression will evaluate to true
, otherwise it will evaluate to false
. The double exclamation marks (!!
) are used to force JavaScript to perform a type conversion and then evaluate the result as a boolean.object['something' + test]
). If the property exists, it will return the value; otherwise, it will return undefined
.Pros and Cons of each approach:
Object.prototype.hasOwnProperty.call(object, 'something' + test)
:hasOwnProperty
method on the Object
prototype, which may incur a small overhead due to prototyping.('something' + test) in object
:in
operator method.!!object['something' + test]
:object['something' + test]
The library being used in this benchmark is none. The test code uses built-in JavaScript features and operators.
As for special JS features or syntax, note that hasOwnProperty
and in
are part of the ECMAScript standard, while !!
coercion is not explicitly mentioned as an issue but may still require consideration due to its behavior in certain situations.
Other alternatives might include using:
object.hasOwnProperty('something' + test)
: This approach avoids accessing the hasOwnProperty
method directly and instead calls it on the object's prototype.Object.keys(object).includes('something' + test)
: This approach uses the keys()
method to get an array of property names, then checks if the desired property is present using the includes()
method.However, these alternatives might not be as concise or efficient as the original approaches, and may incur additional overhead due to the use of built-in methods.