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.reduce((unique, item) => unique.includes(item) ? unique : [unique, item], []);
[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 | 82.9 Ops/sec |
Using lastIndexOf | 346.4 Ops/sec |
Using a Set | 768.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided benchmark tests three different approaches to remove duplicates from an array:
indexOf
(index-based method)lastIndexOf
(index-based method, but with a twist)Each approach is implemented in a separate test case.
Options compared
We have three options being compared:
indexOf
or lastIndexOf
functions to find the index of each item in the array. The main difference between these two methods is that lastIndexOf
returns the last index of the item, whereas indexOf
returns the first index.Pros and Cons
Here are some pros and cons for each approach:
lastIndexOf
may not work as expected if the item is not found in the beginning of the array.Library and purpose
In this benchmark, we can see that two libraries/libraries-like-technologies are used:
Set
(ECMAScript 2015) - which allows to create and store unique values.Special JS feature or syntax
There is no explicit mention of any special JavaScript features or syntax being used in this benchmark. The implementation focuses on simple, standard JavaScript methods.
Other alternatives
In general, other approaches to remove duplicates from an array include:
Map
data structure (similar to a Set, but with additional capabilities)However, these alternatives are not being tested in this specific benchmark.
In summary, the MeasureThat.net benchmark tests three approaches to remove duplicates from an array: index-based methods using indexOf
and lastIndexOf
, and a Set data structure. Each approach has its pros and cons, and we can see that the Set data structure is the fastest and most efficient option in this particular test case.