<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js'></script>
arrayOf1kkNumbers = new Array(100000).fill(1).map((_,index) => index);
const clonedArr = [].concat(arrayOf1kkNumbers);
const clonedArr = [arrayOf1kkNumbers];
const clonedArr = arrayOf1kkNumbers.slice();
const clonedArr = Object.values(arrayOf1kkNumbers);
const clonedArr = Array.from(arrayOf1kkNumbers);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1. concat | |
2. spread | |
3. slice | |
5. Object values | |
6. Array.from |
Test name | Executions per second |
---|---|
1. concat | 706.5 Ops/sec |
2. spread | 683.3 Ops/sec |
3. slice | 1965.5 Ops/sec |
5. Object values | 650.5 Ops/sec |
6. Array.from | 658.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
MeasureThat.net is testing the performance of different methods for shallow cloning an array in JavaScript. Shallow cloning means creating a new copy of the array, but only copying the top-level elements (i.e., no recursive cloning). The test cases use a specific array arrayOf1kkNumbers
with 100,000 elements.
Options being compared
The options being compared are:
Array.prototype.concat()
method to create a new array....
) to create a new array.Array.prototype.slice()
method to create a new array.Object.values()
method to create an array from an object (although this is not strictly shallow cloning, as it uses the object's internal structure).Array.from()
constructor to create a new array.Pros and cons of each approach
Array.from()
constructor (introduced in ECMAScript 2015).Library usage
The test case using lodash
is 5. Object values
. The Object.values()
method is a part of the Lodash library, which provides various utility functions for JavaScript.
Special JS features or syntax
There are no special JS features or syntax used in this benchmark. All tests use standard JavaScript and common array methods.
Other alternatives
If you want to implement your own shallow cloning algorithm, some other options include:
Array.prototype.forEach()
method to iterate over each element of the original array and create a new copy.Array.prototype.map()
method to create a new array with cloned elements, followed by Array.prototype.slice()
to remove the original array from memory.Keep in mind that these alternatives may have different performance characteristics than the methods being tested in this benchmark.
I hope this explanation helps you understand what's going on in this JavaScript microbenchmark!