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.prototype.hasOwnProperty.call(object, 'something' + test)
('something' + test) in object
array.indexOf('something' + test) !== -1
object['something' + test] === true
array.includes('something' + test)
set.has('something' + test)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.prototype.hasOwnProperty | |
Object in | |
Array.indexOf | |
direct | |
Array includes | |
Set has |
Test name | Executions per second |
---|---|
Object.prototype.hasOwnProperty | 4189001.0 Ops/sec |
Object in | 5519183.0 Ops/sec |
Array.indexOf | 1088871.1 Ops/sec |
direct | 5581476.0 Ops/sec |
Array includes | 1091575.6 Ops/sec |
Set has | 6293361.0 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of six different methods to check if a property exists in an object:
Object.prototype.hasOwnProperty.call(object, 'something' + test)
'something' + test
in object
array.indexOf('something' + test) !== -1
object['something' + test] === true
array.includes('something' + test)
set.has('something' + test)
Methods Compared
Here's a brief description of each method, their pros and cons, and other considerations:
Object.prototype.hasOwnProperty.call(object, 'something' + test)
hasOwnProperty
method.hasOwnProperty
call.('something' + test) in object
in
operator to check if a property exists in an object.in
operator call.array.indexOf('something' + test) !== -1
indexOf
method to find an element in an array, then check if the result is not equal to -1 (indicating the absence of the element).indexOf
call.object['something' + test] === true
array.includes('something' + test)
includes
method to check if an element exists in an array.includes
call.set.has('something' + test)
Special Notes
Object.prototype.hasOwnProperty.call
method is not strictly necessary in modern JavaScript versions, as hasOwnProperty
is a built-in method on objects. However, it's still included here to test compatibility with older browsers.array.includes
and set.has
methods are only available in modern browsers (ES11+). Their inclusion here tests compatibility with newer browsers.Alternatives
If you need to support older browsers or specific use cases not covered by this benchmark, consider using:
Object.prototype.hasOwnProperty.call
('something' + test) in object
array.indexOf
(with a custom implementation for the includes
check)Map
or WeakSet
, which may be more suitable for specific use cases.