var array = ["Rome", "Milan", "Barcelona", "Madrid", "Paris", "Nice", "London", "Manchester"];
var clone = [];
clone = Array.prototype.slice.call(array, 0);
for(var i = 0; i < array.length; i++)
{
clone.push(array[i]);
}
clone = Array.prototype.slice.call(array, 0);
var clone2 = [];
while(clone.length > 0)
{
clone2.push(clone.shift());
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice | |
For | |
While |
Test name | Executions per second |
---|---|
Slice | 3326201.5 Ops/sec |
For | 610763.1 Ops/sec |
While | 668171.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark compares three approaches to create a copy of an array: Array.prototype.slice.call()
, for
loop, and while
loop with shift()
method. The goal is to determine which approach is the fastest.
Options Compared
Array.prototype.slice.call()
: This method creates a new array by calling the slice()
method on the original array and passing 0
as the start index.for
loop: This loop iterates over the elements of the original array using an indexer (i
) and pushes each element to a new array (clone
).while
loop with shift()
method: This loop uses a while loop to iterate over the elements of the original array, pushing each element to a new array (clone2
) using the shift()
method.Pros and Cons
Array.prototype.slice.call()
:for
loop:while
loop with shift()
method:shift()
, which returns the first element.Library
None, this benchmark only uses built-in JavaScript features.
Special JS Feature/Syntax
The shift()
method is used in the while
loop approach. The shift()
method returns the first element of an array and removes it from the array. This approach relies on this method to iterate over the elements.
Benchmark Preparation Code
The provided code initializes two arrays: array
containing city names, and clone
/clone2
which will hold the copied values.
Individual Test Cases
Each test case measures the execution time of a specific approach:
Array.prototype.slice.call()
.for
loop to create a copy.while
loop with shift()
method to create a copy.Benchmark Result
The latest benchmark result shows the execution time per second for each test case on a Chrome 95 browser on a Mac OS X 10.15.7 desktop platform:
Based on the benchmark results, the while
loop approach appears to be the fastest.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
Array.prototype.map()
: This method creates a new array by calling the map()
method on the original array.Object.assign()
: This method creates a new object by copying the properties of the original object.Array.from()
: This method creates a new array from an iterable object.Keep in mind that each approach has its pros and cons, and the best choice depends on your specific use case and performance requirements.