var size = 15;
const array = [];
array.length = size;
let index = array.length;
while (index-- > 0) {
const temp = [];
temp.length = size;
array[index] = temp;
}
const array = [];
array.length = size;
let index = array.length;
const temp = [];
temp.length = size;
while (index-- > 0) array[index] = temp.slice(0);
const array = [];
array.length = size;
let index = array.length;
const temp = [];
temp.length = size;
while (index-- > 0) array.push(temp.slice(0));
const array = [];
array.length = size;
let index = size;
while (index-- > 0) {
const temp = [];
temp.length = size;
array.push(temp);
}
const array = Array.from(Array(size), () => {
const temp = [];
temp.length = size;
return temp;
});
const temp = [];
temp.length = size;
const array = Array.from(temp, () => temp.slice());
const array = [];
array.length = size;
let index = array.length;
while (index-- > 0) {
const temp = [];
temp.length = size;
array[index] = temp;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
While Loop with declaration | |
While Loop with Slice | |
While Loop with Push and Slice | |
While Loop with Push | |
Array.from with map | |
Array.from with map and slice | |
While Loop with Slice and Internal Declaration |
Test name | Executions per second |
---|---|
While Loop with declaration | 291005.3 Ops/sec |
While Loop with Slice | 1496097.1 Ops/sec |
While Loop with Push and Slice | 1413510.1 Ops/sec |
While Loop with Push | 287501.0 Ops/sec |
Array.from with map | 227292.5 Ops/sec |
Array.from with map and slice | 665677.4 Ops/sec |
While Loop with Slice and Internal Declaration | 298060.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided benchmark measures the performance of different approaches to create a 2D "square" array filled with arrays of the same length. The benchmark consists of six test cases, each using a distinct method to generate the 2D array.
Test Cases and Approaches
Here's a brief description of each test case and its approach:
push()
method.push()
.push()
method, followed by slicing each element.slice()
.Array.from()
method and the map()
function to generate the 2D array.map()
and slice()
, offering a balance between code simplicity and performance.Other Considerations
When evaluating these approaches, consider factors such as:
Conclusion
Each approach has its strengths and weaknesses. The choice between them depends on the specific requirements of your project, including performance, code complexity, and personal preference. By understanding the trade-offs involved in each method, you can select the most suitable approach for your use case.
In general, Array.from() with map
offers a good balance between simplicity and performance. However, if readability is crucial or you prioritize caching effects due to array indexing patterns, one of the while loop approaches might be more suitable.