let array = Array.from({length:4096},(_,i)=>i).sort(() => Math.random() - 0.5)
let object = array.reduce((pool, item, nth) => {
pool[nth] = item;
return pool;
}, {});
let object = {};
let length = array.length;
for(let i = 0; i < length; i++) {
object[i] = array[i];
}
let object = Object.fromEntries(Object.entries(array))
let object = Object.assign({},array)
let object = {array}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.reduce() | |
For loop | |
Object.fromEntries() + Object.entries() | |
Object.assign() | |
Object ...spread |
Test name | Executions per second |
---|---|
Array.reduce() | 29225.2 Ops/sec |
For loop | 24355.0 Ops/sec |
Object.fromEntries() + Object.entries() | 2106.2 Ops/sec |
Object.assign() | 1285.9 Ops/sec |
Object ...spread | 1519.3 Ops/sec |
The benchmark conducted tests various methods of converting an array to an object in JavaScript, focusing on performance comparisons among different approaches. Here's a breakdown of the options compared, their pros and cons, and other relevant considerations.
Array.reduce()
reduce
method to iterate over the array and construct an object.For Loop
Object.fromEntries() + Object.entries()
Object.fromEntries
to create the object.Object.assign()
Object.assign()
to create a new object from the array.Object ...spread (spread operator)
The latest benchmark results show a clear performance hierarchy among the methods tested:
Array.reduce()
at approximately 29,225 executions per second.For loop
at 24,355 executions per second.Object.fromEntries() + Object.entries()
, Object ...spread
, and Object.assign()
perform significantly worse, with execution speeds decreasing to about 2,106, 1,519, and 1,286 executions per second, respectively.Array.reduce()
is not as performant as a regular for loop, its readability may make it preferable in certain contexts, especially in functional programming paradigms.Map
object could be viable, as it allows for simpler key-value pair management.In conclusion, the choice between these methods relies on individual use cases, balancing the trade-offs of performance, readability, and maintainability.