let arr = [];
for (let i = 0; i < 100000; 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 | 6802.5 Ops/sec |
Array.from array index | 214.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark is designed to compare two approaches for accessing elements in a Uint8Array
:
[]
notation (e.g., a[i]
)Array.from()
method to convert the Uint8Array
to an array, and then accessing elements using the array's indexing syntax (e.g., a[i]
)Benchmark Preparation Code
The script preparation code generates a large array of 100,000 unsigned 8-bit integers (Uint8Array
) and stores it in the variable u8a
. This array will be used as the input for both benchmark test cases.
Individual Test Cases
There are two test cases:
Uint8Array index
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]; // direct access using [] notation
}
This test case directly accesses the elements of u8a
using the []
notation. The variable s
accumulates the sum of all elements.
Array.from array index
const a = Array.from(u8a);
const al = a.length;
let s = 0;
for(let i=0; i<al; i++) {
s += a[i]; // accessing elements using Array.from()
}
This test case converts u8a
to an array using Array.from()
and then accesses the elements using the array's indexing syntax.
Pros and Cons
Direct Access ([]
notation)
Pros:
Cons:
Array.from()
Pros:
Cons:
Library Considerations
The Array.from()
method uses the following libraries:
Array.from()
method, which converts an iterable object (in this case, Uint8Array
) to an array.Array.from()
may rely on additional libraries or frameworks for compatibility.Special JS Features/Syntax
None mentioned in the provided benchmark code. However, it's worth noting that some JavaScript features, such as async/await, may be used in more complex scenarios or future optimizations.
Alternative Approaches
Other approaches to accessing elements in a Uint8Array
might include:
Keep in mind that these alternatives may not be relevant to this specific benchmark and should be evaluated on a case-by-case basis.
The provided benchmark provides valuable insights into the performance differences between direct access and using Array.from()
for accessing elements in a Uint8Array
. By understanding these trade-offs, developers can make informed decisions about which approach best suits their needs.