var arr = [];
for (var i = 0; i < 10000; i++) {
arr.push(Math.floor(Math.random() * 1000) + 1)
}
arr.splice(5000, 0, 0)
var tempResult = arr.filter(v => v !== 0);
var index = arr.indexOf(0);
delete arr[index];
var tempResult = arr;
var index = arr.indexOf(0);
arr.splice(index, 1);
var tempResult = arr;
var index = arr.indexOf(0);
var tempResult = [arr.slice(0, index - 1), arr.slice(index+1)]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter (immutable) | |
indexOf and delete (will leave initial length of array) (mutable) | |
indexOf and splice (mutable) | |
indexOf and slice and spread (immutable) |
Test name | Executions per second |
---|---|
filter (immutable) | 22913.3 Ops/sec |
indexOf and delete (will leave initial length of array) (mutable) | 830730.8 Ops/sec |
indexOf and splice (mutable) | 7961174.5 Ops/sec |
indexOf and slice and spread (immutable) | 7081080.0 Ops/sec |
Benchmark Explanation
The provided benchmark is designed to test the performance of JavaScript arrays in different scenarios: removing an element from an array.
Options Compared
There are four options being compared:
filter()
method without modifying the original array.indexOf()
, deleting it, and then creating a new array by removing the deleted element from the end of the original array.indexOf()
, splicing the element at that index to create a new array with the same length as the original array, but without modifying the original array.slice()
method.Pros and Cons
filter()
method because it avoids creating a new array, but may require more memory allocation and deallocation due to the deletion operation.splice()
method, but may still incur a performance penalty due to the indexing operation.slice()
method, which can be more efficient than other methods for large datasets.Library Usage
The benchmark uses no external libraries, relying solely on the built-in JavaScript features.
Special JS Features or Syntax
There are a few special JS features used in this benchmark:
filter()
method to define the filtering condition.slice()
method calls.Alternatives
Other alternatives for removing elements from an array include:
map()
, forEach()
, or every()``**: These can be used to filter or remove elements from an array without modifying it, similar to the
filter()` method.for...of
loop: This can be used to iterate over the array and remove elements directly, but may require more manual memory management.Note that the choice of approach depends on the specific use case, performance requirements, and personal preference.