var anObject = {
child: {
grandchild: "hello"
}
}
var result = null;
if(anObject){
if(anObject["child"]) {
if(anObject["child"]["grandchild"]){
result = anObject["child"]["grandchild"];
}
}
}
var result = null;
try {
result = anObject["child"]["grandchild"];
}
catch(err) {}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
If | |
Try Catch |
Test name | Executions per second |
---|---|
If | 24006232.0 Ops/sec |
Try Catch | 36738580.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is defined by two test cases: "Try Catch" and "If". The goal of this benchmark is to compare the performance of these two approaches in JavaScript.
Script Preparation Code
The script preparation code defines an object anObject
with a nested structure:
var anObject = {
child: {
grandchild: "hello"
}
}
This object will be used as input for both test cases.
Html Preparation Code
There is no HTML preparation code, which means that this benchmark only runs in a JavaScript environment (not in a web browser).
Test Cases
Let's analyze each test case:
if
statement to access the nested object. The condition checks if anObject.child
is truthy, and if so, it accesses the grandchild
property.var result = null;
if(anObject){
if(anObject[\"child\"]){
if(anObject[\"child\"][\"grandchild\"]) {
result = anObject[\"child\"][\"grandchild\"];\n}
}
}
Pros and Cons of this approach:
anObject
reference)try-catch
block to access the nested object. The code attempts to access the grandchild
property, and if it fails, the catch
block is executed.var result = null;
try {
result = anObject[\"child\"][\"grandchild\"];\n
} catch(err) {}
Pros and Cons of this approach:
anObject
reference)Library/External Dependencies
There are no external libraries or dependencies mentioned in the benchmark definition.
Special JavaScript Features/Syntax
This benchmark does not use any special JavaScript features or syntax, such as async/await, promise chaining, or destructuring.
Alternatives
If you wanted to run this benchmark with different approaches, here are some alternatives:
in
operator: Instead of using the if
statement, you could use the in
operator to check if the property exists.var result = null;
for (var key in anObject) {
if (key === "child" && anObject[key] !== undefined && anObject[key]["grandchild"] !== undefined) {
result = anObject[key]["grandchild"];
break;
}
}
hasOwnProperty
: You could use the hasOwnProperty
method to check if the property exists, like this:var result = null;
if (anObject.hasOwnProperty("child") && anObject.child.hasOwnProperty("grandchild")) {
result = anObject.child.grandchild;
}
These alternatives have similar performance characteristics to the original "If" test case and "Try Catch" test case.