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.findIndex((el) => el === foo);
var newArr = arr.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 | 2350.0 Ops/sec |
filter | 22623616.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the performance of two approaches: findIndex
with splice
, and filter
. The script preparation code creates an array of 15,000 elements, fills it with IDs from 0 to 14,999, and then maps each element to its ID. A random index is generated using Math.random() * 15000
.
Options Compared
The benchmark compares two approaches:
foo
) using findIndex()
, and then removes one element from the original array starting at that index using splice()
.foo
) using the filter()
method.Pros and Cons of Each Approach
Library Usage
The benchmark uses the Math
library for the random()
function and some basic arithmetic operations. The Array.prototype.map()
method is also used, which is a part of the standard JavaScript library.
Special JS Features/Syntax
This benchmark does not explicitly use any special JavaScript features or syntax beyond what's available in standard JavaScript (ES6+). However, it relies on features like array methods (map()
, findIndex()
, splice()
, and filter()
), which are part of the modern JavaScript language.
Alternatives
Some alternative approaches could be:
indexOf()
instead of findIndex()
to find the index of an element.For the specific comparison between FindIndex + Splice
and Filter
, other alternatives could be:
indexOf()
and slicing the array instead of splice()
.slice()
and modifying it.Keep in mind that these alternative approaches may have their own trade-offs and performance characteristics.