var arr = Array.from({ length: 65535 }, (_, index) => index);
var identity = value => value;
var index = 0;
while (++index < 10002) {
arr = arr.map(identity);
arr = Array.from(arr);
arr = arr.slice()
}
((identity, newArr) => newArr = arr.map(e=>e))(identity, [])
var newArr = Array.from(arr)
var newArr = [];
var i = 0;
var length = 65535;
for(; i < length; i++) {
newArr[i] = arr[i];
}
var newArr = [];
for(var i in arr) {
newArr[i] = arr[i];
}
var newArr = arr.slice()
var newArr = [arr];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
array.from | |
for loop | |
forIn | |
slice | |
spred |
Test name | Executions per second |
---|---|
map | 1479.7 Ops/sec |
array.from | 5431.8 Ops/sec |
for loop | 206.4 Ops/sec |
forIn | 96.1 Ops/sec |
slice | 5428.6 Ops/sec |
spred | 5175.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of different methods to copy an array in JavaScript, including Array.from()
, slice()
, spred
(using the spread operator), for loop
, and map
. The test case starts with a large array of 65535 elements created using Array.from()
.
Options Compared
Here's what each option is being tested:
...
) can be used to create a new array by spreading the elements of an existing array.for
loop is used to iterate over each element in the original array and assign it to a new array.Pros and Cons
Here's a brief summary of the pros and cons of each option:
Library Usage
None of the options rely on external libraries.
Special JS Features or Syntax
The benchmark does not use any special JavaScript features or syntax beyond what's available in modern browsers (ECMAScript 2022).
Other Alternatives
If you're interested in exploring other methods to copy arrays, here are a few alternatives:
These alternatives may have different performance characteristics, pros, and cons compared to the options being tested in this benchmark.