Performance Analysis: Duplicating Arrays in JavaScript Using Slice vs. For Loop
In JavaScript, there are multiple approaches to duplicating an array. Two common methods include the slice method and the for loop. This article explores their relative performance to determine which is faster.
Slice Method:
The slice method creates a new array by extracting a specified portion of the original array. The following code shows an example:
var dup_array = original_array.slice();
For Loop:
A for loop iterates through each element of the original array and manually creates a copy in a new array:
for(var i = 0, len = original_array.length; i < len; ++i) dup_array[i] = original_array[i];
Results:
Benchmarks have revealed that the slice method is generally faster for blink-based browsers, such as Chrome and Edge, while the for loop is faster in other browsers, such as Firefox and Safari. This is due to internal optimizations for slice and concat in blink browsers.
In particular, spread syntax (e.g., [...original_array]) and Array.from() have emerged as the fastest methods for array duplication, surpassing both slice and the for loop in most scenarios.
Benchmark Scripts:
The following JavaScript scripts can be executed in the browser's console to compare the performance of the for loop and slice methods:
For Loop:
n = 1000 * 1000; start = +new Date(); a = Array(n); b = Array(n); i = a.length; while (i--) b[i] = a[i]; console.log(new Date() - start);
Slice:
n = 1000 * 1000; start = +new Date(); a = Array(n); b = a.slice(); console.log(new Date() - start);
By running these scripts multiple times, you can observe the relative performance of each method under different browser conditions.
Note: Remember that these methods only perform a shallow copy, meaning that objects referenced within the original array will be shared with the duplicate array. Consider deep cloning techniques for more complex data structures.
The above is the detailed content of Slice vs. For Loop in JavaScript: Which Method Offers Faster Array Duplication?. For more information, please follow other related articles on the PHP Chinese website!