var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
undefined !== obj.d;
'undefined' !== typeof obj.d;
'd' in obj;
obj.hasOwnProperty( 'd' );
!! obj.d;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
undefined | |
typeof | |
in | |
hasOwnProperty | |
bool |
Test name | Executions per second |
---|---|
undefined | 2088645.2 Ops/sec |
typeof | 5649508.0 Ops/sec |
in | 5971808.5 Ops/sec |
hasOwnProperty | 5146062.0 Ops/sec |
bool | 4397868.5 Ops/sec |
Let's break down the provided JSON and benchmark details to understand what is being tested.
Benchmark Definition
The benchmark definition tests the performance of different ways to check if an object property exists or has a specific value. The five test cases are:
undefined !== obj.d;
: checks if obj.d
is not undefined.'undefined' !== typeof obj.d;
: checks if typeof obj.d
(i.e., the type of obj.d
) is not 'undefined'.'d' in obj;
: checks if 'd' is a property of obj
.obj.hasOwnProperty('d');
: checks if obj
has a property named 'd' using the hasOwnProperty
method.!! obj.d;
: checks if obj.d
is truthy (i.e., not false, 0, or an empty string).Options being compared
The benchmark compares the performance of these five test cases across different browsers and devices.
Pros and cons of each approach:
undefined !== obj.d;
: This approach is simple and straightforward. However, it may have a higher overhead due to the !==
operator's use.'undefined' !== typeof obj.d;
: This approach uses the typeof
operator, which can be slower than other methods. Additionally, the comparison involves string literals, which might incur additional overhead.'d' in obj;
: This approach is efficient and straightforward, as it only requires a single operation to check if 'd' exists as a property of obj
. However, it may not be supported by all browsers.obj.hasOwnProperty('d');
: This approach uses the hasOwnProperty
method, which can be slower than other methods due to its additional overhead. Additionally, this method only checks for direct properties, whereas 'd' in obj;
checks all properties of obj
.!! obj.d;
: This approach is a clever trick using the double bang operator (!!
) to convert obj.d
to a boolean value. However, it may not be immediately clear what this test case is checking.Libraries and special JS features
None of these benchmark tests use any specific libraries or special JavaScript features.
Other alternatives
Some alternative approaches for testing object property existence could include:
in
operator with an array to check if a key exists in a map (e.g., { [key]: value }
)has
on the Object.prototype
or Map
objectsHowever, these alternatives are not being tested in this benchmark.