const array = Array.from({length: 10_000}, () => Math.floor(Math.random() * 10_000_000));
const indexToDelete = 7500;
const deleteCount = 500;
const temp = [array];
return temp.filter((x, i) => i < indexToDelete || i >= indexToDelete + deleteCount);
const temp = [array];
temp.splice(indexToDelete, deleteCount);
return temp;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.filter | |
Array.splice |
Test name | Executions per second |
---|---|
Array.filter | 30207.4 Ops/sec |
Array.splice | 500059.7 Ops/sec |
This benchmark tests the performance of two different methods for removing elements from an array in JavaScript: Array.filter
and Array.splice
. Both methods serve the purpose of creating a new array based on certain criteria, but they employ different approaches and have distinct characteristics.
Array.filter
const temp = [...array];
return temp.filter((x, i) => i < indexToDelete || i >= indexToDelete + deleteCount);
filter
method creates a new array populated with elements that pass a test implemented by the provided function. In this case, it checks whether the index of the element is less than the index to delete or greater than or equal to the index plus the count to delete.Array.splice
const temp = [...array];
temp.splice(indexToDelete, deleteCount);
return temp;
splice
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Here, it modifies the copied array directly.filter
for this use case.splice
changes the original).filter
approach.The benchmark results show that:
These results indicate that the Array.splice
method is more performant than Array.filter
for this specific use case.
When choosing between these two methods, consider:
Array.filter
may be your choice. However, if you need better performance for large arrays where you only need to remove items without concern for functional purity, Array.splice
is likely the better option.Other than Array.filter
and Array.splice
, alternatives could include:
reduce
: This approach could combine filtering and mapping functions into a single pass through the array, although it could introduce complexity.In summary, a developer must evaluate the context of their specific use case, readability of code, and performance implications when deciding between Array.filter
and Array.splice
, or considering other methods.