var arr = new Array(15000);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
var index = arr.indexOf(foo);
var copy = arr.slice();
copy.splice(index, 1);
var index = arr.filter(el => el !== foo)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
FindIndex + splice | |
filter |
Test name | Executions per second |
---|---|
FindIndex + splice | 178972.3 Ops/sec |
filter | 782.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The test compares two approaches for removing an element from an array: using indexOf
with splice
, and using filter
.
Script Preparation Code
Before running the benchmarks, the script prepares an array of 15,000 elements, where each element has an id
property that is initially set to 0. The code then maps over the array to update the id
property of each element to its original index in the array.
The script also generates a random number foo
between 0 and 14,999.
Options Compared
There are two approaches being compared:
indexOf
to find the position of foo
in the array, then uses splice
to remove the element at that index.filter
method to create a new array with all elements except for foo
.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
indexOf
, which can be slow for large arrays. Also, splice
modifies the original array.Library and Special JS Features
There are no libraries used in this benchmark, as both approaches rely on built-in JavaScript methods (indexOf
, splice
, and filter
).
Other Considerations
foo
is unique).filter
can be a safer choice when removing elements from an array, as it avoids modifying the original array and creates a new one instead.Alternatives
Other alternatives for removing elements from an array include:
map
to create a new array with the element removed: arr.map((el, idx) => el.id === foo ? undefined : el);
forEach
to iterate over the array and remove elements individually: arr.forEach((el, idx) => { if (el.id === foo) arr.splice(idx, 1); });
Keep in mind that these alternatives may have different trade-offs in terms of memory usage, performance, and code readability.