var arr = new Array(150);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 150);
var index = arr.indexOf(foo);
arr.splice(index, 1);
arr = arr.filter(el => el !== foo)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
FindIndex + splice | |
filter |
Test name | Executions per second |
---|---|
FindIndex + splice | 24225944.0 Ops/sec |
filter | 55239424.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Purpose
The purpose of this benchmark is to compare the performance of two different approaches to remove an element from an array:
indexOf
method to find the index of the target element, and then uses the splice
method to remove it.filter
method to create a new array with all elements that do not match the target element.Comparison
The benchmark compares the execution times of these two approaches for an array of 150 elements. The tests are designed to be similar, so any differences in performance can be attributed to the specific implementation being compared.
Pros and Cons
splice
modifies the original array, which may not be desirable in all cases.Library/Functionality
ES6 Functionality
Benchmark Preparation Code
The preparation code sets up an array arr
with 150 elements, each containing only a unique identifier. The script then fills the array with values from 0 to 149 and maps over it to set the index of each element. Finally, it generates a random index foo
between 0 and 149.
The test cases simply execute the provided benchmark definitions:
arr.indexOf(foo)
followed by arr.splice(index, 1)
.arr.filter(el => el !== foo)
, creating a new array with elements that do not match foo
.Alternatives
Other alternatives for removing an element from an array include:
map
method to create a new array without modifying the original: arr.map((el, idx) => el.id === foo ? null : el)
forEach
method to iterate over the elements and remove them individually.