var original = new Array(100);
for (let r = 0; r < 100; r++) {
original[r] = [];
for (let c = 0; c < 100; c++) {
original[r][c] = r * 100 + c;
}
}
var copy = new Array(original.length);
for (let r = 0; r < original.length; r++) {
copy[r] = original[r].splice(0);
}
var copy = original.map(row => row.splice(0));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
splice | |
map |
Test name | Executions per second |
---|---|
splice | 64149.4 Ops/sec |
map | 362622.0 Ops/sec |
Let's break down the provided benchmark and its results.
Benchmark Definition
The benchmark definition represents a JavaScript code snippet that clones an array of arrays, where each inner array has 100 elements with values generated by multiplying the row index (r) by 100 and adding the column index (c). The goal is to measure how fast different approaches can create a copy of this large two-dimensional array.
Script Preparation Code
The script preparation code creates the original array original
and populates it with data:
var original = new Array(100);
for (let r = 0; r < 100; r++) {
original[r] = [];
for (let c = 0; c < 100; c++) {
original[r][c] = r * 100 + c;
}
}
This code is executed before running the test cases.
Html Preparation Code
The html preparation code is empty, which means it doesn't perform any additional setup or preparation for the benchmark.
Individual Test Cases
There are two test cases:
var copy = new Array(original.length);
for (let r = 0; r < original.length; r++) {
copy[r] = original[r].splice(0);
}
This approach uses Array.prototype.splice()
to remove the first element from each inner array and assign the result to a new array. The copy
variable will contain the cloned data.
var copy = original.map(row => row.splice(0));
This approach uses the Array.prototype.map()
method with a callback function that removes the first element from each inner array and returns the result. The copy
variable will contain the cloned data.
Benchmark Results
The latest benchmark results show the performance of both test cases:
"ExecutionsPerSecond": 362622.0,
This approach executes approximately 362,622 times per second on a Mac with Yandex Browser 24 and Mac OS X 10.15.7.
"ExecutionsPerSecond": 64149.359375,
This approach executes approximately 64,149 executions per second on the same machine.
Comparison of Approaches
Here's a brief comparison of the two approaches:
Array.prototype.splice()
and modifying the original array.Pros and Cons
Pros of map()
:
Cons of map()
:
Pros of splice()
:
Cons of splice()
:
Alternative Approaches
Some alternative approaches for cloning arrays in JavaScript include:
var copy = original.map(row => row.slice());
var copy = original.map(row => row.reduce((a, b) => [b], [])[0]);
const { cloneArray } = require('libya.array');
var copy = cloneArray(original);
Note: These alternative approaches may have different trade-offs in terms of performance, memory usage, and readability.