var length = 100000;
var a = Array.from({
length
}, (e, i) => i+1);
var b = new Set(a);
var c = Object.fromEntries(a.map(e => [e, true]));
var best = 1;
var worst = length;
var middle = length / 2;
return a.includes(best)
return b.has(best)
return c[best]
return a.includes(middle)
return a.includes(worst)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.includes (best scenario) | |
Set.has | |
Object access | |
Array.includes (middle scenario) | |
Array.includes (worst scenario) |
Test name | Executions per second |
---|---|
Array.includes (best scenario) | 114573856.0 Ops/sec |
Set.has | 184906848.0 Ops/sec |
Object access | 161323600.0 Ops/sec |
Array.includes (middle scenario) | 200957.1 Ops/sec |
Array.includes (worst scenario) | 99517.2 Ops/sec |
The benchmark you provided evaluates the performance of different data structures in JavaScript for checking the existence of values. The data structures being compared are:
.includes()
method).has()
method)Array.includes():
Pros:
Cons:
Set.has():
Pros:
Cons:
Object Access:
Pros:
Cons:
The benchmark results show performance measured in executions per second for the various methods across different scenarios.
When choosing between these options, consider:
Use Cases: If you need order or duplicates, Arrays might be appropriate despite their slower performance. If there's a need for fast lookups, prefer Set
or plain Objects.
Memory Usage: Sets and Objects will consume more memory than arrays for large datasets primarily due to their internal structure.
Data Manipulation: If you’re performing a lot of insertions/deletions, Set
and Map
would likely show better performance over arrays due to their optimized nature for handling dynamic data.
Map: Similar to Objects but can use any value as a key instead of just strings, providing more flexibility and avoiding key collisions.
Typed Arrays: For specific cases where performance is critical, and you know the data type, using typed arrays (like Int32Array
) can yield performance benefits over regular arrays.
Binary Search: If dealing with sorted arrays, using binary search could give average-case performance of (O(\log n)). However, this requires that the data be sorted, which adds overhead when inserting/removing elements.
In conclusion, each approach has its pros and cons, and the selection depends heavily on requirements surrounding performance, memory usage, data type, and the specific problem you're trying to solve.