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 newArr = [arr].splice(index, 1);
var index = arr.filter(el => el !== foo)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
splice | |
filter |
Test name | Executions per second |
---|---|
splice | 3339.7 Ops/sec |
filter | 1152.7 Ops/sec |
Let's break down the provided benchmark definition and explanation.
What is tested?
The test measures the performance difference between using splice()
with an array slice (newArr = [...arr].splice(index, 1)
) and using filter()
to create a new array (var index = arr.filter(el => el !== foo)
). The input data consists of an array arr
filled with objects containing an id
property, where each object's id
is set to its original index in the array.
Options compared
There are two main options being compared:
splice()
method to remove a single element from the end of the array. This approach modifies the original array.filter()
method to create a new array with elements that do not match a specified condition (in this case, an object's value equal to the input foo
).Pros and Cons
Splice:
Pros:
Cons:
Filter:
Pros:
Cons:
Other considerations
The test also uses Math.random()
to generate a random index (foo
) for each iteration. This helps distribute the results between the two options across multiple runs.
Library/Language feature usage
None of the provided code snippets use any JavaScript libraries, but they do utilize the following language features:
arr.map((el, idx) => el.id = idx)
[...arr]
)These features are part of modern JavaScript and have been widely adopted in recent versions (ECMAScript 2015+).
Alternatives
Other alternatives for this benchmark could include:
findIndex()
instead of filter()
, which returns the index of the first matching element instead of an array.map()
and then concatenating the results with [...arr]
.However, these alternatives would likely require significant changes to the benchmark definition and test setup.