var size = 0xFFFF;
var buf = new ArrayBuffer(size);
var view = new DataView(buf);
var byte = new Uint8Array(buf);
var data = new Uint8Array(size);
for (let i = 0; i < size; i++) {
data[i] = 100*Math.random();
}
for (let i; i < size; i++) {
view.setUint8(i, data[i]);
}
for (let i; i < size; i++) {
byte[i] = data[i];
}
byte.set(data);
(new Float64Array(buf, 0, size/8))
.set(new Float64Array(data.buffer, 0, size/8));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DataView | |
Uint8Array by byte | |
Uint8Array with set | |
with Float64Array |
Test name | Executions per second |
---|---|
DataView | 65449324.0 Ops/sec |
Uint8Array by byte | 64138916.0 Ops/sec |
Uint8Array with set | 733414.8 Ops/sec |
with Float64Array | 715227.8 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
The benchmark is comparing four different approaches for copying data from an ArrayBuffer
to a JavaScript array:
setUint8()
method on a DataView
object to set the values of an array.Uint8Array
instance and setting its values directly using indexing (byte[i] = data[i];
).set()
method on a Uint8Array
object to set its values.Float64Array
instance from an ArrayBuffer
and setting its values using the set()
method.Now, let's discuss the pros and cons of each approach:
DataView
object, which might be less intuitive for some developers.set()
in the case of large arrays.Float64Array
instance from an ArrayBuffer
. Additionally, it's not as efficient as using optimized methods like set()
on Uint8Array
.Other considerations:
Library usage:
None of the approaches uses any external libraries. However, if you were to write a benchmarking library yourself, you could consider using libraries like numjs
or typedarrays
for optimized array operations.
Special JS features: None of the approaches explicitly uses special JavaScript features like async/await, Promises, or Web Workers. If performance-critical code was being optimized further, you might need to explore these features.
Benchmark preparation code and individual test cases:
The benchmark preparation code sets up an ArrayBuffer
instance and creates a sample array (data
) with random values. The individual test cases provide the Benchmark Definition
strings, which define the loop that will be executed in each approach. These loops set the values of arrays using the different approaches.
Alternatives:
Other alternatives for copying data from an ArrayBuffer
to a JavaScript array include:
atob()
and new Uint8Array(atob(result).split('').map(c => c.charCodeAt(0)))
new ArrayBuffer(size * 8)
, creating a new Uint8Array
instance, and then copying the data from the original array using indexing.Buffer.from()
and new Uint8Array(Buffer.from(data))
Keep in mind that these alternatives might have different performance characteristics depending on the specific use case.