let arr = [];
for (let i = 0; i < 10000; i++)
arr.push(i % 256);
var u8a = new Uint8Array(arr);
const a = u8a; //(u8a as unknown) as number[];
const al = a.length;
let s = 0;
for(let i=0; i<al; i++)
s += a[i];
const a = Array.from(u8a);
const al = a.length;
let s = 0;
for(let i=0; i<al; i++)
s += a[i];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Uint8Array index | |
Array.from array index |
Test name | Executions per second |
---|---|
Uint8Array index | 69101.2 Ops/sec |
Array.from array index | 2463.1 Ops/sec |
Benchmark Explanation
The provided benchmark compares the performance of two approaches to access elements in a Uint8Array:
u8a[i]
is used to access each element. This approach is straightforward and native to JavaScript.Options Compared
The benchmark compares the performance of these two approaches:
u8a[i]
)Pros and Cons of Each Approach
Library Usage
In this benchmark, the Uint8Array
class is used as a native JavaScript object. No external libraries are required.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax being tested in this benchmark.
Other Alternatives
If the Array.from() method is not available or preferred, other alternatives for converting an array-like object to an actual array include:
Array.prototype.slice.call()
(less efficient than Array.from())new Array().push.apply(new Array(), u8a)
(more verbose)However, in modern JavaScript, Array.from() is the recommended and most efficient way to achieve this conversion.
Benchmark Result Interpretation
The provided benchmark result shows the performance of each test case across multiple executions. The first test case performs better, with an execution rate of approximately 69101.25 executions per second, while the second test case has a lower execution rate (2463.099609375 executions per second). This suggests that direct indexing on the Uint8Array object is more efficient than using Array.from() in this specific benchmark.