var object = {},
array = [],
i, test = 10000
for (i = 0; i < 10000; 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)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.hasOwnProperty | |
Object in | |
Array.indexOf | |
direct | |
Array includes |
Test name | Executions per second |
---|---|
Object.hasOwnProperty | 11170897.0 Ops/sec |
Object in | 10310120.0 Ops/sec |
Array.indexOf | 168909.5 Ops/sec |
direct | 10335731.0 Ops/sec |
Array includes | 173754.6 Ops/sec |
Let's dive into the provided benchmark and explore what's being tested.
Benchmark Overview
The provided benchmark compares the performance of four different methods to check if a property exists in an object or array:
object.hasOwnProperty('something' + test)
(something' + test) in object
array.indexOf('something' + test) !== -1
direct
(which checks for equality, assuming the value is always true)What are we comparing?
We're comparing the execution time of these four methods to access a property in an object or array using a variable $test
. The goal is to determine which method is the fastest.
Options Compared
object.hasOwnProperty('something' + test)
: This method checks if the object has a property with the given key. It's a simple and efficient way to check for existence.(something' + test) in object
: This method uses the in
operator, which returns true if the key exists in the object. It's similar to hasOwnProperty
, but can be less efficient due to its broader scope.array.indexOf('something' + test) !== -1
: This method searches for the key in the array and returns 0 if found or -1 if not. The !== -1
check is used to determine existence.direct
: This method checks for equality, assuming the value is always true. It's a simple but potentially slow way to access the property.Pros and Cons of Each Approach
object.hasOwnProperty('something' + test)
: Pros: efficient, precise; Cons: limited by object key structure.(something' + test) in object
: Pros: flexible, can be used with arrays; Cons: may be slower due to broader scope, potential for typos or out-of-scope errors.array.indexOf('something' + test) !== -1
: Pros: flexible, can be used with any data structure; Cons: may be slower due to array search, potential for performance impact on large arrays.direct
: Pros: simple, easy to read; Cons: potentially slow due to unnecessary checks, may not work as expected if value is falsey.Library and Special JS Features
The benchmark uses the following library:
Other Considerations
Alternatives
If you want to write your own JavaScript benchmarks or compare performance of different methods, consider using a library like:
Keep in mind that these alternatives might offer more features and flexibility than MeasureThat.net's built-in benchmarking capabilities.