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)]
const deduped = new Map();
array.forEach((v) => {
if (!deduped.has(v)) {
deduped.set(v, v);
}
});
return Array.from(deduped.values());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using indexOf | |
Using lastIndexOf | |
Using a Set | |
Using a Map |
Test name | Executions per second |
---|---|
Using indexOf | 84.1 Ops/sec |
Using lastIndexOf | 66.8 Ops/sec |
Using a Set | 571.9 Ops/sec |
Using a Map | 394.8 Ops/sec |
I'll break down the explanation into smaller parts to make it easier to understand.
Benchmark Definition and Script Preparation Code
The benchmark is defined in JSON format, which includes:
Name
: A human-readable name for the benchmark (in this case, "Methods to remove duplicates from array x2").Description
: An optional description of the benchmark (not provided in this example).Script Preparation Code
: A JavaScript code snippet that prepares the input data for the benchmark. In this case, it creates an empty array and populates it with 100,000 random integers between 1 and 10.Individual Test Cases
The test cases are defined as an array of objects, each representing a single test to be executed:
Benchmark Definition
: A JavaScript code snippet that defines the specific operation to be performed on the input data. In this case, there are four test cases:indexOf
lastIndexOf
Test Name
: A human-readable name for each test case.Options Compared
The test cases compare the performance of different approaches to remove duplicates from an array:
indexOf
: This approach uses the indexOf
method to check if an element is present in the array.lastIndexOf
: This approach uses the lastIndexOf
method to find the index of the last occurrence of an element.Pros and Cons of Each Approach
Here's a brief summary of the pros and cons of each approach:
indexOf
:lastIndexOf
:indexOf
, but can be slightly faster due to cache locality.Other Considerations
When choosing an approach, consider the following factors:
indexOf
and lastIndexOf
might suffice.Browser-Specific Considerations
The benchmark results are specific to Chrome 114 on a Macintosh desktop with macOS 10.15.7. This means that the performance measurements might not generalize well to other browsers or environments.
As for special JavaScript features or syntax, there's no mention of any specific features being used in this benchmark.