var object = {},
array = [],
set = new Set(),
i, test = 1000;
for (i = 0; i < 1000; i++) {
object['something' + i] = true;
array.push('something' + i);
set.add('something' + i);
}
object.hasOwnProperty('something' + test)
('something' + test) in object
array.indexOf('something' + test) !== -1
object['something' + test]
array.includes('something' + test)
set.has('something' + test)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.hasOwnProperty | |
Object in | |
Array.indexOf | |
direct | |
Array includes | |
Set has |
Test name | Executions per second |
---|---|
Object.hasOwnProperty | 1383059456.0 Ops/sec |
Object in | 1385706240.0 Ops/sec |
Array.indexOf | 784039.2 Ops/sec |
direct | 1570718848.0 Ops/sec |
Array includes | 1265376.1 Ops/sec |
Set has | 1381633792.0 Ops/sec |
I'll break down the provided benchmark definitions and explain what's being tested, along with their pros and cons.
Benchmark Definition
The website MeasureThat.net
allows users to create and run JavaScript microbenchmarks. The provided benchmark definition is:
{
"Name": "Object.hasOwnProperty vs Object in vs Object[] vs Array.indexOf vs Array.includes vs Set.has 2",
"Description": null,
"Script Preparation Code": "...",
"Html Preparation Code": null
}
This benchmark compares the performance of six different approaches to check if a property exists or can be found on an object:
Object.hasOwnProperty
Object in
Object[]
(which is not a valid syntax, but might have been intended as a comparison with array-based indexing)Array.indexOf
Array.includes
Set.has
The pros and cons of each approach are:
Object.hasOwnProperty
:Object in
:hasOwnProperty
, but may be faster due to its use of a special property lookup.Object[]
: As mentioned, this is not a valid syntax and should not be used.Array.indexOf
:Array.includes
:indexOf
, as it returns a boolean value directly.Set.has
:Individual Test Cases
The test cases are defined as:
[
{
"Benchmark Definition": "...",
"Test Name": "..."
},
...
]
Each test case represents one of the six approaches listed above, and their raw execution times are stored in the ExecutionsPerSecond
field.
Other Considerations
RawUAString
field provides additional information about the test environment.Alternatives
If you're looking for alternative approaches or alternatives in JavaScript, some options might include:
in
and has
, which are designed for this purpose.However, it's essential to note that these alternatives might not be as efficient or well-supported as the original approaches listed in the benchmark.