<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
var data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
}
}
}
}
}
R.path(['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'ID'])(data)
data.glossary.GlossDiv.GlossList.GlossEntry.ID
data?.glossary?.GlossDiv?.GlossList?.GlossEntry?.ID
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Ramda path | |
Native path | |
Native path with null check |
Test name | Executions per second |
---|---|
Ramda path | 2837903.2 Ops/sec |
Native path | 16670450.0 Ops/sec |
Native path with null check | 16471182.0 Ops/sec |
I'll break down the provided JSON and explain what's being tested, compared, and the pros/cons of different approaches.
Benchmark Definition
The benchmark tests three ways to access a nested object property in JavaScript: using Ramda's R.path()
function, native JavaScript dot notation (data.glossary.GlossDiv.GlossList.GlossEntry.ID
), and a variant with null checks (data?.glossary?.GlossDiv?.GlossList?.GlossEntry?.ID
).
Comparison
data.glossary.GlossDiv.GlossList.GlossEntry.ID
): This method uses the dot notation to access nested properties directly.R.path()
Function (R.path(['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'ID'])
): This method uses a function to access nested properties using an array of keys.data?.glossary?.GlossDiv?.GlossList?.GlossEntry?.ID
): This method uses optional chaining (introduced in ECMAScript 2020) to access nested properties while handling null or undefined values.Library and Syntax
The benchmark uses Ramda's R.path()
function, which is a utility library for functional programming in JavaScript. It provides a concise way to access nested properties in an array-like object.
There is no special JavaScript feature or syntax used in this benchmark. The focus is on comparing different approaches to accessing nested object properties.
Alternatives
Other alternatives for accessing nested object properties include:
data['glossary']['GlossDiv']['GlossList']['GlossEntry']['ID']
)get()
function, which provides similar functionality to Ramda's R.path()
However, the benchmark focuses on comparing Ramda's R.path()
with native JavaScript dot notation and its variant with null checks.