const testArray = Array(20000).fill().map((_, idx) => idx);
const newTestArray = testArray.splice(0);
const testArray = Array(20000).fill().map((_, idx) => idx);
const newTestArray = testArray.slice();
const testArray = Array(20000).fill().map((_, idx) => idx);
const newTestArray = testArray.concat();
const testArray = Array(20000).fill().map((_, idx) => idx);
const newTestArray = [testArray];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splice | |
Slice | |
Concat | |
Spread |
Test name | Executions per second |
---|---|
Splice | 3444.7 Ops/sec |
Slice | 3380.9 Ops/sec |
Concat | 3287.6 Ops/sec |
Spread | 5110.8 Ops/sec |
I'd be happy to help you understand the JavaScript microbenchmark on MeasureThat.net.
Benchmark Purpose:
The benchmark is designed to compare the performance of different methods for creating a new array from an existing one: splice
, slice
, concat
, and the spread operator (...
).
Options Compared:
splice()
method removes elements from an array and returns an array of the removed elements. It modifies the original array. In this benchmark, it's used to remove the first element from the test array.slice()
method creates a shallow copy of a portion of an array, returning an array with the selected elements. This method does not modify the original array.concat()
method concatenates two or more arrays. It returns a new array and leaves the original arrays unchanged....
) creates a new array by copying elements from an existing array.Pros and Cons of Each Approach:
Other Considerations:
splice
, slice
, or concat
, the methods allocate new memory to store the resulting array. This can lead to performance overhead and higher memory usage....
) was introduced in ECMAScript 2015 (ES6). Older browsers may not support it.Library:
The benchmark doesn't explicitly mention any libraries, but it uses basic JavaScript features like the Array
prototype methods. However, if we consider popular JavaScript frameworks or libraries that might be used with this code, some examples include:
Special JS Features or Syntax: The benchmark doesn't explicitly use any special JavaScript features or syntax beyond the basic array operations and ECMAScript 2015 (ES6) spread operator.
Benchmark Preparation Code:
The provided benchmark preparation code creates a test array with 20,000 elements using Array(20000).fill().map((_, idx) => idx);
, which ensures that all methods have to process the same-sized data. The individual test cases then create new arrays using the respective methods (splice
, slice
, concat
, and spread) and measure their performance.
Alternatives: If you need alternative approaches for creating a new array, consider:
for...of
loop or a map()
function to create an array from an existing one.Keep in mind that these alternatives might not provide the exact same performance as the original methods used in this benchmark.