const data = Array.from({length: 1_000_000}, () => [
Math.random(),
Math.random(),
Math.random(),
]);
let sum1 = 0;
for (let i = 0; i < data.length; i++) {
const [a, b, c] = data[i];
sum1 += a + b + c;
}
let sum2 = 0;
for (let i = 0; i < data.length; i++) {
const arr = data[i];
sum2 += arr[0] + arr[1] + arr[2];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Destructuring | |
Index Access |
Test name | Executions per second |
---|---|
Array Destructuring | 146.2 Ops/sec |
Index Access | 226.1 Ops/sec |
The benchmark "destructuring array keys vs access via index" evaluates two different methods for accessing values from an array of arrays in JavaScript. This comparison helps to understand the performance differences between using array destructuring and accessing array elements via index.
Array Destructuring:
const [a, b, c] = data[i];
a
, b
, and c
.Index Access:
const arr = data[i];
sum2 += arr[0] + arr[1] + arr[2];
From the benchmark results:
This benchmark does not utilize any external libraries; it strictly examines native JavaScript capabilities. The focus remains on analyzing the performance of two built-in syntax features: array destructuring and array indexing.
Readability vs Performance: Depending on the context, developers might prioritize clarity and maintainability over raw performance. In applications where performance is critical, the index access method may be preferable.
TypeScript Considerations: If using TypeScript, destructuring can provide type inference which could be advantageous in larger codebases.
Alternatives:
.forEach()
or .reduce()
may also be considered. However, they might introduce performance overhead due to function calls.Float32Array
) might yield better performance.In summary, this benchmark serves as an excellent case study for developers aiming to understand trade-offs between code clarity and execution performance in JavaScript array manipulation techniques.