var array = [];
for (var i=0; i<300; ++i) {
array.push('00' + i);
}
function hasWithIndexOf(needle) {
return array.indexOf(needle) !== -1;
}
var map = new Map();
array.forEach(item => map.set(item, true));
function hasWithMap(needle) {
return map.get(needle);
}
for (var i=0; i<100; ++i) {
hasWithIndexOf('404');
}
for (var i=0; i<100; ++i) {
hasWithMap('404');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
map |
Test name | Executions per second |
---|---|
indexOf | 29249.9 Ops/sec |
map | 124795.1 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark definition represents two test cases: indexOf
and map
. Both tests aim to measure the performance of finding an element in a list using two different approaches:
indexOf
): The first test uses the array.indexOf()
method to search for the presence of a specific value ("404") within the generated array.Options Compared
The two tests compare the performance of:
indexOf
): This approach uses the array.indexOf()
method to find an element.map
): This approach utilizes a Map object, where each key-value pair is set up in advance.Pros and Cons
indexOf
)Pros:
Cons:
undefined
or null
values)map
)Pros:
Cons:
Other Considerations
indexOf
method in JavaScript performs an iterative search through the array, making it less efficient than hash-based lookups like Map objects.Library and Special JS Features
No notable libraries are used in this benchmark. However, JavaScript's built-in Map
object is employed, which provides a more efficient data structure for searching large datasets.
No Special JS Features are Used
No special JavaScript features or syntax are used beyond the standard array methods and Map objects.
Alternatives
Other alternatives to consider when implementing similar benchmarks:
Keep in mind that this benchmark focuses specifically on comparing array-based search (indexOf
) with Map object search (map
). The alternatives listed above are not necessarily relevant to this particular test case.