const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 30000).reduce((acc, num) => {
return {
acc,
[num]: num
}
}, {})
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 30000).reduce((acc, num) => {
acc[num] = num
return acc
}, {})
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 30000).reduce((acc, num) => {
return Object.assign(acc, {[num]: num})
}, {})
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
const items = range(0, 30000);
let result = {};
for(let item of items) {
result[item] = item;
}
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
const items = range(0, 30000);
let result = {};
for(let i = 0; i < items.length; i += 1) {
result[items[i]] = items[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
with spread operator | |
with mutation | |
with object assign | |
with for...of loop | |
with for loop |
Test name | Executions per second |
---|---|
with spread operator | 0.7 Ops/sec |
with mutation | 741.3 Ops/sec |
with object assign | 25.5 Ops/sec |
with for...of loop | 1132.7 Ops/sec |
with for loop | 1206.1 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance of four different approaches to populate an object with values from a range:
for
loopfor...of
loopObject.assign
)Approach 1: For Loop
This approach uses a traditional for
loop to iterate over the range and assign each value to the object.
Pros:
Cons:
Approach 2: For...Of Loop
This approach uses a for...of
loop, which is more concise and efficient than a traditional for
loop. It also allows for easier iteration over arrays.
Pros:
Cons:
for...of
Approach 3: Mutation
This approach uses direct assignment to add values to the object.
Pros:
Cons:
Approach 4: Spread Operator
This approach uses the spread operator (Object.assign
) to create a new object and assign values from an array.
Pros:
Cons:
Object.assign
Other Considerations
Object.assign
) allows for efficient assignment of values from an array, but it requires careful consideration of the implications of modifying an existing object.for...of
loop provides a more concise and readable alternative to traditional for
loops, but its performance may vary depending on the browser and JavaScript version.Alternative Approaches
Some other approaches that could be considered for this benchmark include:
Overall, this benchmark provides a useful comparison of different approaches to populate an object with values from a range, highlighting the trade-offs between conciseness, readability, and performance.