var randomArray = Array.from({ length: 1000 }, () => Math.floor(Math.random() * 256))
Uint8Array.from(randomArray)
new Uint8Array(randomArray)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test Uint8Array.from() | |
Test new Uint8Array() |
Test name | Executions per second |
---|---|
Test Uint8Array.from() | 80690.5 Ops/sec |
Test new Uint8Array() | 107662.5 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
What is being tested?
The benchmark compares two methods of creating a Uint8Array
object:
new Uint8Array()
: This method creates a new, empty Uint8Array
object using the JavaScript constructor.Uint8Array.from()
: This method creates a new Uint8Array
object from an iterable (in this case, a random array).Options being compared
The two options are:
new Uint8Array()
(tested in one test case)Uint8Array.from()
(tested in another test case)Library usage
There is no explicit library usage in this benchmark. However, it's worth noting that Uint8Array
is a built-in JavaScript class, so no external library is required.
Special JS feature or syntax
The test case uses the Array.from()
method, which was introduced in ECMAScript 2015 (ES6). This method creates a new array from an iterable by calling the specified callback function on each element of the original iterable. In this case, the callback function is simply returning the value of Math.floor(Math.random() * 256)
, which generates random integers between 0 and 255.
Other alternatives
There are other ways to create a Uint8Array
object in JavaScript:
new Uint8Array([1, 2, 3])
Uint8Array
prototype's from()
method with an array literal: Uint8Array.from([1, 2, 3])
However, these alternatives are not being tested in this benchmark.
Other considerations
When creating a Uint8Array
object, it's essential to consider performance and memory efficiency. For large arrays, using the constructor-based creation method can be more efficient, as it allows the browser to use its internal buffer management. However, for smaller arrays or when readability is more important than performance, the Array.from()
method can be a better choice.
In this benchmark, the results indicate that new Uint8Array()
might be slightly faster on iOS 16 devices, while Uint8Array.from()
seems to have a slight advantage on other platforms.