var size = 0xFF;
var buf = new ArrayBuffer(size);
var view = new DataView(buf);
var byte = new Uint8Array(buf);
var data = [];
var nativeArr = new Array(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, 0);
for (let i; i < size; i++) {
nativeArr[i] = data[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DataView | |
Uint8Array by byte | |
Uint8Array with set | |
Native Array |
Test name | Executions per second |
---|---|
DataView | 12911557.0 Ops/sec |
Uint8Array by byte | 12899118.0 Ops/sec |
Uint8Array with set | 736197.0 Ops/sec |
Native Array | 12828039.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark tests the performance of three different approaches for setting data in an array:
DataView
Uint8Array
by byteNative Array
Each test case measures the execution time for setting each individual element of the array.
Options Compared
Here are the options being compared:
DataView
: a binary view of an ArrayBuffer, providing direct access to its underlying bytes.Uint8Array
by byte: using a Uint8Array constructor with a specific length and then setting each individual element individually.Native Array
: using a native JavaScript array constructor.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
DataView
:Uint8Array
by byte:Native Array
:Library/Functionality Used
In this benchmark, the following library/functionality is used:
DataView
: a built-in JavaScript API providing direct access to ArrayBuffer views.Uint8Array
by byte: a constructor provided by the Web APIs (Specifically, the Uint8Array
constructor).Native Array
: a native JavaScript array constructor.Special JS Feature/Syntax
In this benchmark, no special JS feature or syntax is used beyond the standard API functions and constructors. However, it's worth noting that some modern browsers may optimize certain operations using SIMD (Single Instruction, Multiple Data) instructions or other advanced techniques.
Other Alternatives
If you'd like to explore alternative approaches for setting data in an array, consider the following options:
Buffer
object instead of Uint8Array
.typedarrays
or bigint-typedarray
for high-performance typed arrays.Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case and performance requirements.