var user = [{id: '1001', name: 'Octavio', age: 46},{id: '2020', name: 'Mara', age: 39},{id: '3456', name: 'Alanis', age: 12},{id: '9876', name: 'Alondra', age: 10},{id: '6589', name: 'Ariana', age: 7},];
var username = { 1001: "Octavio", 2020: "Mara", 3456: "Alanis", 9876: "Alondra", 6589: "Ariana"};
var userage = { 1001: 46, 2020: 39, 3456: 12, 9876: 10, 6589: 7};
user.find(x => x.name === 'Alanis').name;
user.find(x => x.name === 'Alanis').age;
username[3456];
userage[3456];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array | |
object |
Test name | Executions per second |
---|---|
array | 1628167.0 Ops/sec |
object | 1625832.6 Ops/sec |
Measuring performance differences between objects and arrays in JavaScript.
The benchmark test case, defined in the JSON, measures how fast JavaScript can access elements of an array versus accessing them through an object's index.
Here are the options compared:
Array Access
user.find(x => x.name === 'Alanis').name;
indexOf()
or findIndex()
: Not used in the test case, but generally faster than direct indexing when the array has a large number of elements.map()
or reduce()
: Not used in the test case.Object Access
username[3456];
userage[3456];
(similar to direct indexing, but with a more verbose syntax)Additional Considerations
find()
method is not used in this test case because it involves searching for an element that doesn't exist (for user.find(x => x.name === 'Alanis')
), making direct indexing or bracket notation a better choice.Library and Syntax Used
None of the test cases use any external libraries. The syntax used, such as array and object methods, is standard JavaScript.
Special JS Feature or Syntax Used
The benchmark definition uses arrow functions (x => x.name === 'Alanis'
) to define functions inline within the find()
method. This feature was introduced in ECMAScript 2015 (ES6) and provides a concise way to define small anonymous functions.
Other Alternatives
To compare array and object access performance, alternative approaches could include:
forEach()
or for...of
loops: Instead of direct indexing or bracket notation.Note that these alternatives would require modifications to the benchmark definition and test cases to accommodate the changes.