var array = [];
for (let i = 0; i < 100000; i++) {
array.push(Math.floor((Math.random() * 10) + 1));
}
array.filter((item, index) => array.indexOf(item) != index);
array.filter((item, index) => array.lastIndexOf(item) != index);
[new Set(array)]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using indexOf | |
Using lastIndexOf | |
Using a Set |
Test name | Executions per second |
---|---|
Using indexOf | 251.7 Ops/sec |
Using lastIndexOf | 139.1 Ops/sec |
Using a Set | 741.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is designed to measure the performance of different methods for removing duplicates from an array. The script preparation code generates an array of 100,000 random integers, which is then used as input for the benchmarking tests.
Test Cases
There are three test cases:
array.indexOf(item) != index
to check if an item exists in the array. If it does, indexOf
returns its index; otherwise, it returns -1.array.lastIndexOf(item) != index
to check if an item exists in the array. Like indexOf
, it returns its index if found or -1 if not found.[...new Set(array)]
to create a new set from the original array. Since sets only allow unique values, this approach removes duplicates.Comparison
The benchmark compares the performance of these three approaches:
indexOf
and lastIndexOf
are similar in that they both iterate over the array to find the index of each item.Pros and Cons
indexOf
can stop iterating as soon as it finds a match. However, its performance degrades significantly with large arrays due to the linear search.indexOf
, this approach has similar strengths and weaknesses. Its performance is better than indexOf
for very large arrays since it can take advantage of the array's internal indexing.Library and Special JS Features
In this benchmark, no external library is used. The JavaScript engine itself handles the processing of arrays and sets.
There are no special JavaScript features or syntax being tested in this benchmark. All standard features are being used.
Other Alternatives
Some alternative approaches to removing duplicates from an array include:
filter()
with a predicate function that checks for uniqueness, e.g., array.filter((item, index) => array.indexOf(item) === index)
.uniq
function.Keep in mind that the choice of approach depends on the specific use case and requirements.