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), 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) | 22639.7 Ops/sec |
indexOf and delete (will leave initial length of array) (mutable) | 829148.6 Ops/sec |
indexOf and splice (mutable) | 7939405.0 Ops/sec |
indexOf and slice and spread (immutable) | 7079069.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Context
The provided JSON represents a benchmark for removing an element from an array in JavaScript. The script preparation code generates a large array with 10,000 random integers and sets its fifth element to 0. The benchmark consists of four test cases:
indexOf
method to find the index of the desired element, then deletes it using the splice
method.splice
directly without checking if the element is present first.slice
method to create a new array with elements before the index of the desired element, and then spreads the remaining elements into a new array using the spread operator (...
).filter
method to create a new array with elements that do not match the condition (i.e., non-zero values).Library Used
There is no explicitly mentioned library in the provided JSON, but it's likely that the benchmarks are running in a Node.js environment with the built-in JavaScript features.
Special JS Features/Syntax
The benchmarks use the following special JS features/syntax:
slice
method...
)filter
methodHowever, it's worth noting that the indexOf
and splice
methods are not new features. They have been part of the JavaScript language since its inception.
Options Compared
The benchmarks compare the performance of four different approaches to remove an element from an array:
indexOf
and splice
or delete
to remove the element.slice
and spread operator (...
) to create a new array with elements before the index of the desired element.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
slice
and spread operator):Other Considerations
When evaluating these benchmarks, consider the following:
slice
and spread operator may exhibit better cache locality than indexOf
and splice
.Alternatives
If you're looking for alternative approaches or want to explore other JavaScript features, consider:
indexOf
.async/await
, Generator functions
, or Symbolic references
.