foo = {
bar: {
baz: {
qux: {
aaa: {
bbb: {
ccc: {
ddd: {
eee: {
fff: 123
}
}
}
}
}
}
}
}
};
foo?.bar?.baz?.qux?.aaa
foo && foo.bar && foo.bar.baz && foo.bar.baz.qux && foo.bar.baz.qux.aaa
(_foo = foo) === null || _foo === void 0 ? void 0 : (_foo$bar = _foo.bar) === null || _foo$bar === void 0 ? void 0 : (_foo$bar$baz = _foo$bar.baz) === null || _foo$bar$baz === void 0 ? void 0 : (_foo$bar$baz$qux = _foo$bar$baz.qux) === null || _foo$bar$baz$qux === void 0 ? void 0 : _foo$bar$baz$qux.aaa;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Native | |
babel-loader |
Test name | Executions per second |
---|---|
Optional Chaining | 7981397.5 Ops/sec |
Native | 1522443.6 Ops/sec |
babel-loader | 496223.1 Ops/sec |
What is being tested?
MeasureThat.net is testing the performance of three different approaches to access nested properties in an object: Optional Chaining (?.
), Native code, and Babel Transform.
Options compared:
?.
) to access nested properties. It returns undefined
if any of the properties are null or undefined.babel-transform
) to achieve the same result as Optional Chaining.Pros and Cons:
Library used:
In the provided benchmark, babel-loader
is used as a transformation library to enable Optional Chaining in environments that don't support it natively. The babel-transform
option is specified in the Benchmark Definition JSON.
Special JS feature or syntax:
Optional Chaining (?.
) is a relatively recent addition to JavaScript, introduced in ECMAScript 2020. It allows accessing nested properties with a concise syntax, making code more readable and expressive.
Other alternatives:
If you need to support older browsers or environments that don't support Optional Chaining, you may consider using other approaches, such as:
if
statements) to access nested properties.Keep in mind that each approach has its own trade-offs and potential performance implications. MeasureThat.net's benchmark helps you understand the relative performance of these approaches in different scenarios.