for (i = 0; i < 10; i++) {
}
const object = {
property1: 1
}
Object.setPrototypeOf(object, {
property2: 2
});
const result = object.hasOwnProperty('property1');
const object = {
property1: 1
}
Object.setPrototypeOf(object, {
property2: 2
});
const result = object.property1 ? true : false;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
hasOwnProperty | |
classical if |
Test name | Executions per second |
---|---|
hasOwnProperty | 348025.3 Ops/sec |
classical if | 458604.9 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance difference between two approaches to check if a property exists in an object: hasOwnProperty
and classical if-conditional checks.
Options Compared
Two options are compared:
hasOwnProperty
: This method is part of the Object interface and returns a boolean value indicating whether the specified property exists in the object.in
operator.Pros and Cons
hasOwnProperty
:
Pros:
Cons:
Classical if-conditional check:
Pros:
Cons:
hasOwnProperty
, as it also searches for the property's value.Library Used
The Object
library is used, which provides the hasOwnProperty
method. This method is part of the ECMAScript standard and is implemented in native JavaScript, making it fast and efficient.
Special JS Feature/Syntax
None mentioned in this benchmark. However, if you're interested in exploring other features, some notable examples include:
let
and const
declarations for variable hoisting=>
) for concise function expressions${}
) for string interpolationOther Alternatives
Some alternative approaches to check if a property exists in an object include:
in
operator with a try-catch block: if (obj.hasOwnProperty('property')) { ... }
Object.keys()
method and checking if the array contains the property name: if (Object.keys(obj).includes('property')) { ... }
hasOwnProperty
function that can be used instead of the native implementation.For this benchmark, the comparison between hasOwnProperty
and classical if-conditional checks is likely intended to demonstrate the performance difference between these approaches.