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('foo' in n === false)
break;
}
var n = {};
while(true) {
if(!('foo' in n))
break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
test truth | |
test undefined | |
test hasOwnProperty | |
test in === | |
test in ! |
Test name | Executions per second |
---|---|
test truth | 1078204800.0 Ops/sec |
test undefined | 12296229.0 Ops/sec |
test hasOwnProperty | 160367280.0 Ops/sec |
test in === | 1127436672.0 Ops/sec |
test in ! | 1126103936.0 Ops/sec |
This benchmark investigates the performance of different ways to check if a property exists in an object in JavaScript:
!n.foo
(Test Name: test truth
): This uses a simple logical negation (!
). If the property foo
doesn't exist on the object n
, accessing it will return undefined
. The exclamation mark negates this, resulting in true
.
n.foo === undefined
(Test Name: test undefined
): This explicitly compares the value of n.foo
to undefined
using strict equality (===
).
!n.hasOwnProperty('foo')
(Test Name: test hasOwnProperty
): This utilizes the built-in hasOwnProperty()
method, which directly checks if a property is owned by the object itself. It returns false
for non-existent properties and true
otherwise.
'foo' in n === false
(Test Name: test in ===")
. This uses the in
operator to check if foo
is a property of n
. The result is compared with false
using strict equality (===
).
Let's break down the pros and cons:
!n.foo
:
n.foo === undefined
:
hasOwnProperty()
for large objects due to the strict equality check.!n.hasOwnProperty('foo')
:
'foo' in n === false
:
!n.hasOwnProperty('foo')
. hasOwnProperty()
depending on JavaScript engine implementations.Alternatives:
While the benchmark focuses on these methods, other techniques exist:
_.has
, _.get
).Let me know if you have any more questions or need further clarification!