size = 15000
array = Array.from({ length: size }, (v, i) => i)
object = Object.assign({}, Array.from({ length: size }, (v, i) => i))
const a = array[12000]
const o = object[12000]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array access | |
object access |
Test name | Executions per second |
---|---|
array access | 15530098.0 Ops/sec |
object access | 16802088.0 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and other considerations.
Benchmark Definition
The provided JSON defines two benchmark tests:
array access vs object access
array access
and object access
Script Preparation Code
The script preparation code generates two arrays and objects with 15,000 elements each:
size = 15000
array = Array.from({ length: size }, (v, i) => i)
object = Object.assign({}, Array.from({ length: size }, (v, i) => i))
This creates an array array
and an object object
with the same elements.
Individual Test Cases
The two individual test cases are:
array access
: const a = array[12000]
object access
: const o = object[12000]
These test cases access specific elements in the arrays and objects, respectively.
Library: Object.assign
In the script preparation code, Object.assign
is used to create the object object
. This function creates a new object by copying all enumerable own properties from one or more source objects into a target object. In this case, it's used to copy the array elements into an object.
Special JS Feature: Array.from
The script preparation code uses Array.from
, which is a JavaScript method that returns a new Array instance created with a specified constructor and arguments. This feature allows for concise creation of arrays from iterables like objects or arrays.
Comparison Approach
The benchmark compares two approaches:
array[12000]
)object[12000]
)This comparison is likely meant to test the performance difference between accessing elements in arrays and objects.
Pros and Cons
Other Considerations
object
is created using Object.assign
, which may not be the most efficient way to create an object with many properties.Alternatives
There are other alternatives for creating arrays and objects, such as:
Array.prototype.map
or Array.prototype.forEach
to create an array with specific valuesObject.keys()
or Object.entries()
to iterate over object properties and create a new objectHowever, these alternatives may not provide the same level of performance optimization as using Array.from
and Object.assign
, respectively.