var stringArray = Array.from({
length: 9999
}, () => `${Math.floor(Math.random() * 100)}`);
const setSpread = [ new Set(stringArray)]
const arrayFromSet = Array.from(new Set(stringArray))
const filteredArray = stringArray.filter((i,index) => stringArray.indexOf(i) === index)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set spread | |
Set array from | |
Filtered array |
Test name | Executions per second |
---|---|
Set spread | 5987.7 Ops/sec |
Set array from | 5837.1 Ops/sec |
Filtered array | 261.9 Ops/sec |
Let's break down the provided JSON benchmark definition and test cases.
Benchmark Definition
The benchmark measures performance differences between three approaches:
const setSpread = [... new Set(stringArray)]
).Array.from()
method (const arrayFromSet = Array.from(new Set(stringArray))
).stringArray.indexOf(i) === index
).Options Comparison
Here's a brief overview of each approach:
delete
method.Array.from()
. It also preserves the original order of elements, unlike the spread operator.stringArray.indexOf(i) === index
, which may be slower than set-based operations for large datasets. Also, this approach does not preserve uniqueness.Library and Special JS Features
...
): This operator is used to create a new array by spreading the elements of an iterable (like an array or set).Alternative Approaches
For performance-critical benchmarks like this one, you might want to consider alternative approaches such as:
Set.prototype.delete()
, Set.prototype.has()
) can be faster than the spread operator or Array.from()
method.stringArray.indexOf(i) === index
, you could directly access elements at their corresponding indices in the original array, skipping unnecessary lookups.Keep in mind that benchmarking is all about finding the most efficient approach for your specific use case. You may need to experiment with different techniques and test them thoroughly before making a conclusion.