var data1 = [ Array.from(Array(10000).keys()) ];
var data2 = [ Array.from(Array(1000).keys()) ];
const filteredArray = data1.filter(value => data2.includes(value));
const filteredArray = data1.filter(Set.prototype.has, new Set(data2));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter and includes | |
set |
Test name | Executions per second |
---|---|
filter and includes | 574.7 Ops/sec |
set | 3362.4 Ops/sec |
Let's dive into the details of this benchmark.
Benchmark Name: List vs Set
Description: This benchmark compares the performance of filtering an array using two different methods: Array.prototype.includes()
and Set.prototype.has
.
Test Cases:
filter()
method on an array (data1
) and checking if each element exists in another array (data2
) using includes()
.filter()
method on an array (data1
) and checking if each element exists in a set (new Set(data2)
) using the has()
method.Used Library: None
Special JS Feature or Syntax: Set.prototype.has
is a method that checks if a value exists in the set. It's not a special feature, but rather a built-in method of the Set
object.
Other Alternatives:
Map
instead of an array for storing unique values and using the has()
method.Array.prototype.some()
method, which can provide better performance than filter()
.The results show that the "set" approach outperforms the "filter and includes" method on this particular benchmark. This is likely due to the more efficient lookup operation provided by the set data structure.