var object = {},
array = [],
i, test = 1000;
for (i = 0; i < 1000; i++) {
object['something' + i] = true;
array.push('something' + i);
}
object.hasOwnProperty('something' + test)
('something' + test) in object
array.indexOf('something' + test) !== -1
object['something' + test] === true
array.includes('something' + test)
Object.hasOwn(object, 'something' + test)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.hasOwnProperty | |
Object in | |
Array.indexOf | |
direct | |
Array includes | |
has |
Test name | Executions per second |
---|---|
Object.hasOwnProperty | 5246364.5 Ops/sec |
Object in | 4942895.5 Ops/sec |
Array.indexOf | 1045242.4 Ops/sec |
direct | 4953886.5 Ops/sec |
Array includes | 1029488.4 Ops/sec |
has | 3413079.0 Ops/sec |
I'll break down the provided benchmark and its test cases, explaining what's being tested, compared options, pros/cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of different approaches for checking if a property exists in an object or array. It creates a large object and array with 1000 properties/elements, then uses each test case to check if a randomly generated string is present in the object/array.
Test Cases
hasOwnProperty
method.in
operator.indexOf
method.object['something' + test]
equals true
.includes
method.Object.hasOwnProperty
.Comparison
The benchmark compares the performance of these six approaches:
Object.hasOwnProperty
: Uses the hasOwnProperty
method to check for property existence.Object in
: Uses the in
operator to check if a key exists.Array.indexOf
: Searches for the string using the indexOf
method.direct
: Directly accesses the object/array element.Array includes
: Checks if the string is included in the array.has
: Same as Object.hasOwnProperty
.Pros and Cons
hasOwnProperty
for small objects and arrays.Object.hasOwnProperty
.Other Considerations
in
operator, especially in older browsers.includes
on very large arrays may be slower due to iteration.Alternatives
If you need alternative approaches, consider:
Keep in mind that these alternatives might not be available or supported by all browsers, so consider the target environment when choosing an approach.