var array = [];
var map = new Map();
var obj = {};
for (var i = 0; i < 2000; i++){
array.push(Math.random());
map.set(i,true);
obj[i]=true;
}
var sorted = array.sort()
function binaryIndexOf(searchElement) {
var minIndex = 0;
var maxIndex = this.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = this[currentIndex];
if (currentElement < searchElement) {
minIndex = currentIndex + 1;
}
else if (currentElement > searchElement) {
maxIndex = currentIndex - 1;
}
else {
return currentIndex;
}
}
return -1;
}
sorted.includes(5)
binaryIndexOf.call(sorted, 5)
map.has(5);
obj[5]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
binary | |
Map.has() | |
Obj[] |
Test name | Executions per second |
---|---|
Includes | 491243.8 Ops/sec |
binary | 19182264.0 Ops/sec |
Map.has() | 70701072.0 Ops/sec |
Obj[] | 71325104.0 Ops/sec |
Let's break down the provided JSON data and explain what's being tested.
Overall Benchmark
The benchmark measures the performance of different ways to check for existence in an array or object:
sorted.includes(5)
(using the includes()
method)binaryIndexOf.call(sorted, 5)
(using a custom binary search algorithm)map.has(5);
(using the Map.prototype.has()
method)obj[5]
(direct indexing into an object)Script Preparation Code
The script preparation code creates:
array
)map
) and populates it with 2000 random key-value pairsobj
)Library Used: None ( native JavaScript methods)
All four test cases use only built-in JavaScript methods, without importing any external libraries.
Test Cases
Each test case measures the performance of a specific method:
Includes
: Uses the includes()
method to search for an element in a sorted array.binary
: Uses a custom binary search algorithm to find an element in a sorted array.Map.has()
: Uses the Map.prototype.has()
method to check if a key exists in a Map object.Obj[]
: Directly indexes into an object using square brackets ([]
) to access a value.Pros and Cons
Here's a brief summary of the pros and cons for each approach:
Other Considerations
includes()
can lead to a faster result if the array contains duplicate elements.Benchmark Result Interpretation
The provided benchmark results show that:
Obj[]
> binary
> Map.has()
).Keep in mind that these results may not generalize to other browsers or environments.