var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
if(undefined !== obj['d']){}
if('undefined' !== typeof obj['d']){}
if('d' in obj){}
if(obj.hasOwnProperty( 'd' )){}
if(!!obj['d']){}
if(obj['d']!==undefined){}
if(obj['d']!=undefined){}
if(obj['d']==undefined){}
if(obj['d']){}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
undefined | |
typeof | |
in | |
hasOwnProperty | |
bool | |
Undefined2 | |
undefined3 | |
undefined4 | |
bool2 |
Test name | Executions per second |
---|---|
undefined | 91090528.0 Ops/sec |
typeof | 219349440.0 Ops/sec |
in | 132360544.0 Ops/sec |
hasOwnProperty | 131976752.0 Ops/sec |
bool | 219486352.0 Ops/sec |
Undefined2 | 95855224.0 Ops/sec |
undefined3 | 96450120.0 Ops/sec |
undefined4 | 96566920.0 Ops/sec |
bool2 | 233647312.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition JSON
The benchmark definition JSON provides the necessary information to run the tests. Here's what we have:
Name
: The name of the benchmark, which is "undefined vs. typeof vs. in vs. hasOwnProperty 32".Description
: A brief description of the benchmark, which is "Object lookup performance".Script Preparation Code
: A JavaScript code snippet that creates an object with properties a
, b
, c
, d
, and e
. This code will be executed before each test.Html Preparation Code
: An empty string, indicating that no HTML preparation code is required.Individual Test Cases
We have 8 individual test cases, each defining a different scenario for testing object lookup performance. Here's what we need to know about each:
undefined
.in
operator.hasOwnProperty()
method.undefined
.What's being tested?
We're testing how fast JavaScript can look up properties in an object using different operators or methods. The idea is to see which approach is fastest for this particular task.
Options compared
The main options being compared here are:
in
(using the in
operator)hasOwnProperty()
(using a method)===
, !==
, and other comparison operators!!obj['d']
, obj['d'] === undefined
, etc.)Pros and Cons
Here's a brief summary of each option:
in
, but may be slower due to the method call.===
, !==
): Quick and straightforward, but may have issues with handling undefined
values.!!obj['d']
, etc.): Fast and simple, but may not account for all edge cases.Library
None of these options rely on a specific library.
Special JavaScript features or syntax
None of the test cases use any special JavaScript features or syntax beyond what's commonly found in modern JavaScript implementations. However, some versions of in
might have issues with handling certain types of objects (e.g., objects with undefined properties).
Other alternatives
If you were to modify this benchmark to test other scenarios, here are a few ideas:
These alternatives could provide more insight into JavaScript's performance capabilities and help identify potential optimization opportunities.