c = new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255])
let stream = new Uint8Array()
let a = 1000
while (a --> 0) {
const buf = new Uint8Array(stream.length + c.length);
buf.set(stream, 0);
buf.set(c, stream.length);
stream = buf;
}
let stream = []
let a = 1000
const push = Array.prototype.push;
while (a --> 0) {
push.apply(stream, c)
new Uint8Array(stream)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Uint8Array | |
Array |
Test name | Executions per second |
---|---|
Uint8Array | 1445.3 Ops/sec |
Array | 803.9 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches for resizing arrays in JavaScript: Uint8Array
and native JavaScript Array
. The test aims to determine which approach is faster and more efficient.
Script Preparation Code
The script preparation code creates a constant array c
containing 20 values (represented as 255
, which is the maximum value for an unsigned 8-bit integer).
Benchmark Test Cases
There are two individual test cases:
Uint8Array
instance and resizes it by concatenating another Uint8Array
instance (stream
) with the constant array c
. The resulting array is then reassigned to the original stream
variable.push()
method of native JavaScript arrays to add elements from the constant array c
to an empty array stream
. After each iteration, a new Uint8Array
instance is created and assigned to stream
.Library Used
The Uint8Array
class is used in the first test case. This is a built-in JavaScript class that provides a typed array for representing 8-bit unsigned integers.
Special JS Feature/Syntax
None are explicitly mentioned in the benchmark code, but it's worth noting that modern JavaScript engines have various optimizations and features that may impact performance, such as:
However, these effects are usually subtle and not directly related to the specific syntax or features used in this benchmark.
Performance Considerations
When comparing the two approaches:
push()
method, which may incur additional overhead due to:However, modern JavaScript engines are optimized for native array operations, and the performance difference between these two approaches is likely to be small in practice.
Other Alternatives
There are other ways to resize arrays in JavaScript:
concat()
method: stream = stream.concat(c)
set()
method with a buffer-like object (e.g., new ArrayBuffer()
)lodash
or array-clone
These alternatives may offer different performance characteristics, but they are not part of the benchmarked test cases.
Overall, the benchmark is designed to compare two specific approaches for resizing arrays in JavaScript and determine which one performs better. The results can help developers understand the trade-offs involved in using typed arrays versus native arrays, depending on their use case and performance requirements.