const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const copy = data.slice(3, 8)
const copy2 = data.slice(0, 3)
const copy = [];
const copy2 = [];
for(let i = 0; i < data.length; i++) {
if (i >=3 ) {
copy.push(data[i]);
} else {
copy2.push(data[i]);
};
};
const copy = [];
const copy2 = [];
data.forEach((el, i) => {
if (i >=3 ) {
copy.push(el);
} else {
copy2.push(el);
};
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
for loop | |
forEach |
Test name | Executions per second |
---|---|
slice | 30059190.0 Ops/sec |
for loop | 13028219.0 Ops/sec |
forEach | 34328528.0 Ops/sec |
In the provided benchmark definition, the performance of three different methods for slicing an array in JavaScript is tested. The benchmark compares the execution speed of the Array.prototype.slice
, a traditional for
loop, and the forEach
method. The following is a detailed explanation of these approaches:
Array.slice()
const copy = data.slice(3, 8)
const copy2 = data.slice(0, 3)
slice
method creates a shallow copy of a portion of an array into a new array object. It takes two arguments: the start and end indices. In this benchmark, it slices the original array into two separate arrays.for loop
const copy = [];
const copy2 = [];
for(let i = 0; i < data.length; i++) {
if (i >= 3) {
copy.push(data[i]);
} else {
copy2.push(data[i]);
}
}
for
loop manually iterates over the array, checking the index to decide which element to push into which of the two arrays.Array.forEach()
const copy = [];
const copy2 = [];
data.forEach((el, i) => {
if (i >= 3) {
copy.push(el);
} else {
copy2.push(el);
}
});
forEach
method executes a provided function once for each array element. Here, it’s used to decide where to push each element based on the index.The latest benchmark results show the average number of executions per second for each method on a specific browser:
forEach: 34,328,528 exec/sec
slice: 30,059,190 exec/sec
for loop: 13,028,219 exec/sec
Overall Performance: Choosing between these methods often depends on the specific use case. For read-heavy applications where performance is crucial, slice
likely offers the best balance of clarity and performance. In cases with more complex logic that requires early termination or more control over iteration, a for
loop might be preferred.
Browser Differences: Performance can vary across different browsers and JavaScript engines. What's fast in one environment may not be in another, so testing in the target environment is crucial.
Alternatives: Other methods for array manipulation include map
, filter
, and reduce
, which could be leveraged for different purposes but are not directly applicable for slicing in the same manner as the tested methods.
In conclusion, this benchmark effectively illustrates the differences in performance and usability among common JavaScript array manipulation methods, providing essential insights for software engineers making decisions based on performance considerations.