const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 10).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, 10).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, 10).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, 10);
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, 10);
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 | 1752811.5 Ops/sec |
with mutation | 9694777.0 Ops/sec |
with object assign | 388366.2 Ops/sec |
with for of loop | 9808419.0 Ops/sec |
with for loop | 8310622.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Definition
The benchmark is defined as a JavaScript function range
that generates an array of numbers from 0 to a specified number to
. The function uses a for loop to iterate over the range and push each number into an output array.
Test Cases
...
) is used to create a new object with the current number as its key and value.acc
) is modified directly by assigning a new property with the current number as its key and value.Object.assign
method is used to create a new object with the current number as its key and value. This approach creates a new object, similar to the spread operator.Library Used: None of the test cases use any external libraries.
Special JS Feature/Syntax: The benchmark uses modern JavaScript features such as:
...
)=>
)\r\n
)However, these features are not specific to the benchmark itself and can be used in other contexts without affecting their performance.
Other Alternatives: If you wanted to optimize this benchmark for performance, you could consider using:
Array.prototype.forEach()
instead of a traditional for loopObject.create()
instead of creating an object with ...
or Object.assign()
Keep in mind that these optimizations may come at the cost of readability and maintainability.