var length = 1e6;
var f32_a = Float32Array.from({length}, Math.random);
var f32_b = Float32Array.from({length}, Math.random);
var f64_a = Float64Array.from({length}, Math.random);
var f64_b = Float64Array.from({length}, Math.random);
var arr_a = Array.from({length}, Math.random);
var arr_b = Array.from({length}, Math.random);
for (let i = 0; i < length; i++) {
f32_a[i] = f32_b[i];
}
for (let i = 0; i < length; i++) {
f64_a[i] = f64_b[i];
}
for (let i = 0; i < length; i++) {
arr_a[i] = arr_b[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
iterate and set f32 | |
iterate and set f64 | |
iterate and set array |
Test name | Executions per second |
---|---|
iterate and set f32 | 394.8 Ops/sec |
iterate and set f64 | 386.1 Ops/sec |
iterate and set array | 449.4 Ops/sec |
The benchmark presented tests the performance of iterating over different types of array-like structures in JavaScript: Float32Array
, Float64Array
, and regular JavaScript Array
. Each data structure has unique characteristics that can influence performance, particularly in contexts involving numerical computations.
Float32Array:
for (let i = 0; i < length; i++) { f32_a[i] = f32_b[i]; }
Float32Array
is a typed array that represents an array of 32-bit floating-point numbers. It is suitable for applications where memory usage is critical and precision is not as important (e.g., graphics processing).Float64Array
.Float64Array:
for (let i = 0; i < length; i++) { f64_a[i] = f64_b[i]; }
Float64Array
stores 64-bit floating-point numbers, providing more precision than Float32Array
. This is important for numerical analysis or computational tasks where accuracy is paramount.Float32Array
, which may slow down performance in scenarios with large datasets.Standard JavaScript Array:
for (let i = 0; i < length; i++) { arr_a[i] = arr_b[i]; }
The benchmark results indicate the execution speed of each approach in terms of iterations per second. Here are the results:
Typed Arrays (Float32Array and Float64Array): These arrays allow for a better structured memory layout, which can lead to better performance for numerical operations compared to standard JavaScript arrays. This is especially relevant in performance-critical applications such as graphics or numerical simulations.
Memory and Performance Trade-offs: Depending on the application's requirements—whether higher precision is needed for calculations or memory efficiency is the priority—developers must choose between these options. In performance-sensitive environments, especially when processing large datasets, profiling different approaches is advisable.
By understanding the characteristics, advantages, and disadvantages of each option, software engineers can make informed decisions about which data structure to utilize based on specific use cases and performance requirements.