var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var u8 = new Uint8Array(data);
var copy = u8.subarray(10, 20);
var copy = u8.slice(10, 20);
var copy = new Uint8Array(u8.subarray(10, 20));
var copy = new Uint8Array(u8.slice(10, 20));
var copy = new Uint8Array(10).set(u8.subarray(10, 20));
var copy = new Uint8Array(10).set(u8.slice(10, 20));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
subarray direct | |
slice direct | |
subarray copy | |
slice copy | |
subarray set | |
slice set |
Test name | Executions per second |
---|---|
subarray direct | 6081745.5 Ops/sec |
slice direct | 7280128.5 Ops/sec |
subarray copy | 3488912.8 Ops/sec |
slice copy | 3831527.5 Ops/sec |
subarray set | 4028675.5 Ops/sec |
slice set | 4818551.5 Ops/sec |
Measuring the performance of different approaches to create a subset or copy of an array is crucial in understanding how JavaScript engines optimize array operations.
The benchmark tests four different ways to create a subset of an array:
subarray(start, end)
method.slice(start, end)
method.new Uint8Array()
and then setting the values using set()
.Let's analyze each approach:
Subarray and Slice:
These two methods are similar, as they both return a new array containing the elements from the original array, starting at the specified index start
and ending at end
. However, there is a subtle difference between them. When using slice()
, the method returns an object with length
property equal to end - start
, whereas subarray()
returns an object with length
equal to end - start + 1
. This means that if you're sure about the length of the subset, slice()
is faster. If you're not sure, subarray()
might be a better choice.
Copy and Set:
Creating a new array by copying elements from an original array using new Uint8Array()
and then setting its values is generally slower than creating an array with slice()
or subarray()
. However, this approach can be beneficial when you need to create an exact copy of the original array without modifying it.
Performance Comparison: According to the latest benchmark results, the order of performance from fastest to slowest is:
Other Considerations:
Array.prototype.slice()
or Array.prototype.subarray()
can be faster than using Array.prototype.slice.call()
, as it avoids creating an intermediate object.In summary, when measuring the performance of different approaches to create a subset of an array, it's essential to understand the differences between slice()
and subarray()
. Creating a new array by copying elements from the original array using new Uint8Array()
and then setting its values is generally slower than using slice()
or subarray()
, but can be beneficial when you need an exact copy.