var arr = Array.from({length: 10000}, () => Math.random())
var other = arr.slice();
var other = [ arr ]
var other = []
arr.forEach(el => other.push(el))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice | |
spread operator | |
Push operation |
Test name | Executions per second |
---|---|
Array.prototype.slice | 172210.7 Ops/sec |
spread operator | 107884.9 Ops/sec |
Push operation | 29459.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
The provided JSON represents a benchmark test case that compares three different approaches for creating a copy of an array: Array.prototype.slice()
, the ES6 spread operator ([ ...arr ]
), and the push()
method with a loop (arr.forEach(el => other.push(el))
). The test is focused on performance, specifically measuring how many executions per second each approach can handle a large array of 100,000 elements.
Options compared:
[ ...arr ]
): This operator creates a new array with all the elements of the original array, creating a deep copy.var other = []\r\narr.forEach(el => other.push(el))
): This approach creates a new array by pushing each element of the original array into it.Pros and cons of each approach:
[ ...arr ]
):slice()
for very large arrays due to the additional overhead of creating an iterator and iterating over the elements.var other = []\r\narr.forEach(el => other.push(el))
):slice()
due to the additional overhead of the loop and push operations.Library used:
None explicitly mentioned in this test case. However, it's likely that the benchmark uses internal JavaScript functions or libraries like V8 (the engine behind Google Chrome) to execute the code.
Special JS feature/syntax:
No special features or syntax are highlighted in this test case.
Other alternatives:
For creating copies of arrays, other methods exist:
Array.from()
: Creates a new array from an iterable source (like another array). This method is often used for creating large arrays and can be faster than slice()
for very large arrays.Array.prototype.map()
: Creates a new array by calling a provided function on each element of the original array. While not ideal for copying, it can be used in combination with other methods to achieve similar results.In summary, this benchmark test case provides a useful comparison of three different approaches for creating an array copy: traditional slice()
, ES6 spread operator, and push operation with a loop. The choice of method depends on the specific requirements and performance characteristics of your use case.