var a = [Array(1000)].map(_ => Math.random());
var ta = (new Float32Array(1000)).map(_ => Math.random());
a.reverse();
ta.reverse();
for (let i = 0; i < 10000; ++i)
a[i] = a[i] + 1;
for (let i = 0; i < 10000; ++i)
ta[i] = ta[i] + 1;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array reverse | |
typedArray reverse | |
array i/o | |
typedArray i/o |
Test name | Executions per second |
---|---|
array reverse | 853012.1 Ops/sec |
typedArray reverse | 2047312.0 Ops/sec |
array i/o | 13019.7 Ops/sec |
typedArray i/o | 17672.8 Ops/sec |
The benchmark titled "array vs Float32Array" evaluates the performance differences between standard JavaScript arrays and typed arrays, specifically the Float32Array
, in handling common operations.
Benchmark Options:
a
): These are flexible, general-purpose data structures in JavaScript that can hold elements of any type.ta
): This is a typed array that represents an array of 32-bit floating-point numbers. Typed arrays offer improved performance for certain computations, particularly when dealing with large volumes of numerical data.Test Cases:
a.reverse();
): This operation reverses the order of elements in the standard array.ta.reverse();
): This does the same for the Float32Array
.for (let i = 0; i < 10000; ++i) a[i] = a[i] + 1;
): This operation modifies each element of the standard array by incrementing it by one.for (let i = 0; i < 10000; ++i) ta[i] = ta[i] + 1;
): Similarly, this increments each element of the Float32Array
.Standard Arrays (Array
):
Typed Arrays (Float32Array
):
reverse()
natively constructed into their prototype, so operations may require more code or specific handling.Float32Array
significantly outperforms standard arrays in almost all operations:This demonstrates that operations involving typed arrays can be much faster due to the optimized handling of data types.
Memory Usage: Typed arrays can be more memory-efficient because they store data in a contiguous block of memory, which can limit overhead and improve cache performance compared to standard JavaScript arrays that may have a variety of data types.
Other Alternatives:
Float32Array
, JavaScript provides several other typed arrays like Int32Array
, Uint8Array
, and others, optimized for different types of numeric data and use cases.In conclusion, while both standard arrays and typed arrays have their uses, choosing the right one depends on the specific performance and flexibility requirements of the application. This benchmark provides valuable insight into how these data structures perform specifically on numerical tasks.