var array = [];
for (var i=0; i<300; ++i) {
array.push('00' + i);
}
function hasWithIndexOf(needle) {
return array.indexOf(needle) !== -1;
}
var map = new Set();
array.forEach(item => map.add(item));
function hasWithMap(needle) {
return map.has(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 |
---|---|
array | |
map |
Test name | Executions per second |
---|---|
array | 22376.2 Ops/sec |
map | 2174710.2 Ops/sec |
Let's dive into explaining the provided JSON benchmark data.
Benchmark Definition
The provided JSON defines two benchmarks:
Set
and indexOf()
to an array (push()
and includes()
methods). The benchmark script creates an array with 300 elements, each represented as a string in the format "00" followed by a number from 0 to 299. Two functions are defined: hasWithIndexOf(needle)
for the array approach and hasWithMap(needle)
for the Set approach.The script initializes an empty Set (map
) and populates it with elements from the array using forEach()
method. The functions hasWithIndexOf(needle)
and hasWithMap(needle)
check if a given value is present in the array or Set, respectively.
Options Compared
The benchmark compares two approaches:
push()
and includes()
methods)forEach()
method to populate it)Pros and Cons of Each Approach
indexOf()
.Other Considerations
forEach()
method is used to populate the Set, but it's not clear if this is an optimal implementation for large datasets.Library and Special JS Features
The benchmark uses the following JavaScript library:
Set
is a built-in JavaScript object (introduced in ECMAScript 2015).There are no special JavaScript features used in this benchmark.