var itemCount = 1000
var items = new Array(itemCount)
for (var i = itemCount - 1; i >= 0; i--) {
items[i] = { id: i, data: 920501 }
}
const itemsById = {}
for (let i = items.length - 1; i >= 0; i--) {
itemsById[items[i].id] = items[i]
}
const itemsById = {}
for (const item of items) {
itemsById[item.id] = item
}
const itemsById = items.reduce((result, item) => {
return { result, [item.id]: item }
}, {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
for-of loop | |
reduce |
Test name | Executions per second |
---|---|
for loop | 5578.1 Ops/sec |
for-of loop | 62593.4 Ops/sec |
reduce | 2402.9 Ops/sec |
I'll provide an explanation of the provided benchmark, its options, pros and cons, library usage, special JS features, and other considerations.
Benchmark Description
The provided JSON represents a JavaScript microbenchmark test case that compares three different approaches to iterate over an array and convert it to an object with id
values as keys:
Benchmark Preparation Code
The preparation code is identical for all three approaches:
var itemCount = 1000;
var items = new Array(itemCount);
// Initialize array with objects containing 'id' and 'data' properties
for (var i = itemCount - 1; i >= 0; i--) {
items[i] = { id: i, data: 920501 };
}
Options Comparison
Here's a brief summary of the three approaches:
for (var i = items.length - 1; i >= 0; i--) {
itemsById[items[i].id] = items[i];
}
for (const item of items) {
itemsById[item.id] = item;
}
const itemsById = items.reduce((result, item) => {
return { ...result, [item.id]: item };
}, {});
Library Usage
The Array.prototype.reduce()
method is a built-in method in modern JavaScript. However, some older browsers may not support it natively. If needed, polyfills or library imports can be used to ensure compatibility.
Special JS Feature: For-Of Loop
The for...of loop was introduced in ECMAScript 2015 (ES6) and is a new iteration syntax that allows iterating over arrays and other iterable objects without manual indexing. It's designed to be more concise and expressive than traditional for loops.
In this benchmark, the for-of loop provides an efficient and modern approach to iterating over the array, but it may not be supported in older browsers or environments.
Other Considerations
When choosing between these approaches, consider the following factors: