var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const arr2 = [arr];
const arr3 = arr.slice(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
slice |
Test name | Executions per second |
---|---|
spread | 2095073.8 Ops/sec |
slice | 5598239.5 Ops/sec |
Let's dive into the details of this benchmark.
Benchmark Definition
The benchmark is called "Array clone" and it involves cloning an array in JavaScript. The preparation code creates an array arr
with 20 elements.
Test Cases
There are two test cases:
...
) to create a shallow copy of the original array.slice()
method to create a shallow copy of the original array.Library
No external library is used in this benchmark.
Special JS feature or syntax
The spread operator (...
) is a special feature introduced in ECMAScript 2015 (ES6). It allows you to expand an iterable (such as an array) into individual elements. In this case, it's used to create a new array by spreading the contents of the original array.
Pros and Cons
Here's a brief comparison of the two approaches:
slice()
for large arrays, as it involves creating a new array and iterating over each element.Other Alternatives
Here are some other ways to clone an array in JavaScript:
concat()
method to create a new array by concatenating the original array with an empty array. This approach is slower than spread and slice, but may be useful if you need to clone multiple arrays.Overall, this benchmark demonstrates a simple example of how to measure the performance differences between two common approaches to cloning an array in JavaScript.