var randomArray=Array.from({length: 1000}, () => Math.floor(Math.random() * 100));
for (let i = randomArray.length - 1; i >= 0; --i) {
if (randomArray[i] != 1) {
continue;
}
randomArray.splice(i, 1);
}
return randomArray;
var newArray = [];
for (let i = randomArray.length - 1; i >= 0; --i) {
if (randomArray[i] == 1) {
continue;
}
newArray.push(randomArray[i]);
}
return newArray;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splice | |
Copy to new |
Test name | Executions per second |
---|---|
Splice | 265120.0 Ops/sec |
Copy to new | 43305.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Overview
The test compares two approaches for removing elements from an array: splice
(Splice) and creating a new array using Array.from
(Copy to new).
Script Preparation Code
The script preparation code creates a random array of 1000 integers between 0 and 100:
var randomArray = Array.from({length: 1000}, () => Math.floor(Math.random() * 100));
This array is used as input for both test cases.
Test Cases
There are two individual test cases:
splice
to remove elements from the original array:for (let i = randomArray.length - 1; i >= 0; --i) {
if (randomArray[i] != 1) {
continue;
}
randomArray.splice(i, 1);
}
return randomArray;
Array.from
and copies the desired elements:var newArray = [];
for (let i = randomArray.length - 1; i >= 0; --i) {
if (randomArray[i] == 1) {
continue;
}
newArray.push(randomArray[i]);
}
return newArray;
Library and Syntax
In this benchmark, Array.from
is used to create a new array. This is a modern JavaScript feature introduced in ECMAScript 2015.
Options Compared
The two test cases compare the performance of:
splice
method to remove elements from the original array.Array.from
and copies the desired elements.Pros and Cons
Here are some pros and cons of each approach:
Splice
Pros:
Cons:
Copy to new
Pros:
splice
for large arraysCons:
Other Considerations
When choosing between splice
and Array.from
, consider the following:
splice
can be a convenient option. However, if you're working with large arrays or performance is critical, Array.from
might be a better choice.Array.from
is the way to go.Alternatives
Other alternatives for removing elements from an array include:
filter()
methodsome()
and findIndex()
methodsHowever, these approaches may have different performance characteristics or require additional memory allocation compared to splice
and Array.from
.