var a = [1];
var b = new Set([1]);
var c = new Map([[1, 1]]);
return a.includes(1);
return b.has(1);
return c.has(1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array includes | |
Set has | |
Map has |
Test name | Executions per second |
---|---|
Array includes | 110556576.0 Ops/sec |
Set has | 144808336.0 Ops/sec |
Map has | 140204864.0 Ops/sec |
This benchmark compares the performance of different ways to check for the presence of an element in a collection in JavaScript, specifically focusing on the Array.includes()
, Set.has()
, and Map.has()
methods. Below is a detailed explanation of each approach, its pros and cons, as well as possible alternatives.
Array.includes():
return a.includes(1);
true
or false
. Set.has():
return b.has(1);
Map.has():
return c.has(1);
Examining the benchmark results, we see the following executions per second for each method:
From these results, Set.has()
provided the best performance, followed closely by Map.has()
, with Array.includes()
being significantly slower.
Use Case: The choice of method should depend on the use case. For simple checks in small datasets, using Array.includes()
is adequate. For larger datasets needing frequent existence checks, Set.has()
or Map.has()
would be ideal.
Memory Usage: When working with large datasets, consider the trade-off between speed and memory usage. Sets and Maps may require more memory, but in terms of performance for lookups, they are advantageous.
Data Types: If only primitive data types are being checked, Set
or Array
are appropriate. For structured data requiring associations, prefer Map
.
Array.includes()
, you could manually loop through an array, but this is not recommended due to poor performance compared to the native method._.includes()
) that may provide additional functionality, but they come with additional overhead in terms of package size.In conclusion, this benchmark highlights the performance differences between working with primitive data checks in JavaScript collections. Depending on your application requirements—like size, speed, and memory consumption—one method may suit your needs more efficiently than the others.