var n = {};
while(true) {
if(!n.foo)
break;
}
var n = {};
while(true) {
if(n.foo===undefined)
break;
}
var n = {};
while(true) {
if(!n.hasOwnProperty('foo'))
break;
}
var n = {};
while(true) {
if(n.foo==null)
break;
}
var n = {};
while(true) {
if(n.foo==undefined)
break;
}
var n = {};
while(true) {
if(!Object.prototype.hasOwnProperty(n,'foo'))
break;
}
var n = {};
while(true) {
if(!Object.hasOwn(n, 'foo'))
break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
test false | |
test undefined | |
test hasOwnProperty | |
test == null | |
test == undefined | |
test static hasOwnProperty | |
test static hasOwn |
Test name | Executions per second |
---|---|
test false | 914821184.0 Ops/sec |
test undefined | 8332570.5 Ops/sec |
test hasOwnProperty | 87819920.0 Ops/sec |
test == null | 904887360.0 Ops/sec |
test == undefined | 8271383.0 Ops/sec |
test static hasOwnProperty | 3519068.2 Ops/sec |
test static hasOwn | 7855440.0 Ops/sec |
Let's break down the test cases and the options being compared.
What is tested?
The benchmark tests different ways to check if a property exists on an object. The properties being checked are foo
, bar
(not mentioned in the provided benchmark definition, but present in some test cases), and other special values like undefined
, null
, and undefined member
.
Options compared:
!property_exists
: Directly checks if a property exists using the in
operator or the hasOwnProperty
method.== null
with a logical test !(property_value === null)
to check if a value is not equal to null
.undefined
: Replaces == undefined
with a logical test (property_value !== undefined)
, but since undefined
is not a number, this test might behave unexpectedly.hasOwnProperty
: Uses the static method Object.prototype.hasOwnProperty.call(obj, prop)
to check if a property exists on an object.hasOwn
: Uses the non-static method Object.hasOwn(obj, prop)
to check if a property exists on an object.Pros and Cons:
!property_exists
:in
operator or hasOwnProperty
method.undefined
), and can lead to confusing code if not used carefully.undefined
:undefined
type.undefined
.hasOwnProperty
:hasOwn
:hasOwnProperty
, but with better support for objects that may not have the prototype chain defined.Other considerations:
!property_exists
is usually sufficient.== null
, as they can lead to confusion and unexpected results. Instead, use the simpler != null
check or directly compare with null
.hasOwn
), so consider this when choosing an approach.In conclusion, while there are pros and cons to each option, !property_exists
remains the most straightforward and efficient choice for simple property existence checks. However, logical tests can be useful in specific scenarios where readability and expressiveness are important.