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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using indexOf | |
Using lastIndexOf |
Test name | Executions per second |
---|---|
Using indexOf | 96.8 Ops/sec |
Using lastIndexOf | 76.8 Ops/sec |
I'll explain what's being tested in the provided JSON benchmark.
Benchmark Overview
The benchmark tests two different approaches to filter an array and remove all duplicate values: using indexOf
and using lastIndexOf
. The goal is to determine which approach is faster.
Script Preparation Code
The script preparation code creates an array of 100,000 random integers between 1 and 10. This array will be used as the input for the filter function.
Html Preparation Code
There is no HTML preparation code provided, so this step is skipped.
Individual Test Cases
There are two individual test cases:
indexOf
method to check if an item exists in the array. If it does not exist at the current index, the item is included in the filtered array.lastIndexOf
method to check if an item exists in the array. If it does not exist at the current index, the item is included in the filtered array.Pros and Cons of Each Approach
lastIndexOf
, since indexOf
can return -1 immediately if the item is not found.lastIndexOf
can stop searching once it finds the first occurrence of the item.indexOf
overall, as it has to search the entire array from the start.Other Considerations
indexOf
may throw a TypeError, while lastIndexOf
may throw an RangeError).Library Used
None. This benchmark uses only built-in JavaScript functions: array.filter()
, indexOf()
, and lastIndexOf()
.
Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax that would be unfamiliar to most software engineers.
Alternatives
For removing duplicates from an array, other approaches include:
Object.assign()
, then use the spread operator (...
) to create a new array with unique elements.These alternatives may have different performance characteristics than the benchmark's two approaches, but can also be useful in certain situations.