var buffer1 = new ArrayBuffer(1024 * Float64Array.BYTES_PER_ELEMENT);
var array = new Float64Array(buffer1);
var buffer2 = new ArrayBuffer(1024 * Float64Array.BYTES_PER_ELEMENT);
var view = new DataView(buffer2);
for (let i = 0; i < 1024; i += 1) {
if (i === 0) {
array[i] = 1;
} else {
array[i] = array[i-1] + i;;
}
}
for (let i = 0; i < 1024; i += 4) {
if (i === 0) {
view.setFloat64(i, 1);
} else {
view.setFloat64(i, view.getFloat64(i - 1) + i);
}
}
for (let i = 0; i < 1024; i += 1) {
if (i === 0) {
array[i] = 1;
} else {
array[i] = array[i-1] + i;;
}
}
for (let i = 0; i < 1024; i += 4) {
if (i === 0) {
view.setFloat64(i, 1);
} else {
view.setFloat64(i, view.getFloat64(i - 1) + i);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[i] = i; | |
view.setFloat64(i, i) | |
array[i] = i; 2 | |
view.setFloat64(i, i) 2 |
Test name | Executions per second |
---|---|
array[i] = i; | 306217.9 Ops/sec |
view.setFloat64(i, i) | 274843.6 Ops/sec |
array[i] = i; 2 | 305752.8 Ops/sec |
view.setFloat64(i, i) 2 | 273932.1 Ops/sec |
The benchmark outlined in the provided JSON compares the performance of two different approaches to handling numerical data in JavaScript: using TypedArray
(specifically Float64Array
) versus using DataView
.
TypedArray (Float64Array):
array[i] = i;
array[i] = i; 2
Float64Array
is a typed array that represents an array of 64-bit floating-point numbers. It provides a way to handle binary data and allows for efficient storage and manipulation of numerical data.DataView:
view.setFloat64(i, i)
view.setFloat64(i, i) 2
DataView
object allows for read and write operations with buffers that have a defined byte order. It provides a more flexible way to manipulate binary data compared to typed arrays, allowing you to work with various data types in a single buffer.The benchmarks measure the number of executions per second achieved by each approach:
TypedArray:
array[i] = i;
: 306,217.91 executions per secondarray[i] = i; 2
: 305,752.81 executions per secondDataView:
view.setFloat64(i, i)
: 274,843.56 executions per secondview.setFloat64(i, i) 2
: 273,932.09 executions per secondPros:
Cons:
Pros:
Cons:
Use Cases:
TypedArray
when operations primarily involve numerical calculations, as it generally delivers better performance.DataView
when working with mixed data types or binary formats where memory layout needs to be explicitly controlled.Alternatives:
In summary, while TypedArray
generally provides better performance for straightforward numeric operations, DataView
offers more flexibility for handling various data types and structures within a single buffer. The choice between them should depend on the specific requirements of the application in terms of performance and data handling capabilities.