var array = Array.from({ length: 100 }).map((val, i) => i);
var messages = array.slice().splice(38, 1);
var messages = [array].splice(38, 1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice & Splice | |
ES6 Array Creation |
Test name | Executions per second |
---|---|
Slice & Splice | 10704300.0 Ops/sec |
ES6 Array Creation | 10654868.0 Ops/sec |
This benchmark tests the performance of two different approaches to creating a new array that excludes one element from an existing array in JavaScript:
1. slice()
and splice()
:
slice()
: Creates a shallow copy of a portion of an array without modifying the original. splice()
: Modifies the original array by removing elements at a specific index range.The code snippet array.slice().splice(38, 1)
first creates a copy of the array
using slice()
and then uses splice()
to remove one element from that copy (at index 38).
2. ES6 Array Spread Syntax:
...
) allows you to expand an array into its individual elements within a new array literal.The code snippet [...array].splice(38, 1)
first uses the spread operator to create a new array containing all the elements of the original array
, and then modifies that new array using splice()
to remove one element (at index 38).
Pros & Cons:
slice()
& splice()
:
ES6 Array Spread Syntax:
Other Considerations:
splice()
vs. slice()
: The choice between these two methods depends on whether you need to modify the original array or simply create a new one without changes.filter()
method:const newArray = array.filter((val, i) => i !== 38);
Test Results:
In this specific benchmark, the ES6 Array Spread Syntax slightly outperforms the traditional slice() & splice()
approach. This result is consistent with the generally expected performance advantage of using modern JavaScript features like spread syntax.