function fromNumberToObject(id = 0) {
return {
id,
value: id + id,
name: 'example',
};
}
var list = [Array(30000).keys()].map(fromNumberToObject);
list.slice();
[list];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.slice | 159025.1 Ops/sec |
spread operator | 135973.3 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition:
The benchmark compares two approaches to creating an array of objects:
Array.prototype.slice()
method...
)Script Preparation Code:
function fromNumberToObject(id = 0) {
return {
id,
value: id + id,
name: 'example',
};
}
var list = [...Array(30000).keys()].map(fromNumberToObject);
This code creates an array of 30,000 objects using the fromNumberToObject
function and the spread operator (...
). The fromNumberToObject
function returns an object with three properties: id
, value
, and name
. The key
values are generated from [Array(30000).keys()]
, which creates an array of numbers from 0 to 29,999.
Html Preparation Code: (not provided)
Since the HTML preparation code is not provided, we assume that it's empty or doesn't affect the benchmarking results.
Individual Test Cases:
There are two test cases:
list.slice();
[...list];
These test cases compare the performance of creating an array using the slice()
method versus the spread operator (...
).
Pros and Cons of Different Approaches:
...
):slice()
.slice()
.Library Usage:
None explicitly mentioned in the provided code. However, the spread operator uses the Array.prototype.slice()
method internally to create an array-like object from which it extracts elements.
Special JavaScript Features/Syntax:
...
) was introduced in ECMAScript 2015 (ES6) and provides a more concise way to create arrays or objects by "spreading" existing values.slice()
method is a built-in Array prototype method that creates a shallow copy of an array.Other Alternatives:
For creating an array of objects, you could also consider using:
Array.from()
with an iterator or array-like object.Array.of()
(ES6) with the spread operator.However, in this specific benchmark, only two approaches are being compared: the traditional slice()
method and the ES6 spread operator (...
).