var randomStringsToGenerate = 10000;
var array = [];
var set = new Set();
var object = {};
var map = new Map();
for (let i = 0; i < randomStringsToGenerate; i++) {
array.push(i);
map.set(i, true);
object[i] = true;
set.add(i);
}
return array.includes(5000)
return set.has(5000)
return object[5000]
return map.has(5000)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array | |
set | |
object | |
map |
Test name | Executions per second |
---|---|
array | 143841.0 Ops/sec |
set | 12059111.0 Ops/sec |
object | 12792256.0 Ops/sec |
map | 12246240.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The website MeasureThat.net
provides a JSON representation of a JavaScript microbenchmark, which consists of:
Individual Test Cases
There are four individual test cases:
return array.includes(5000)
return set.has(5000)
return object[5000]
return map.has(5000)
Options Compared
The benchmark compares four different approaches to check for value existence:
includes()
method or iterating through the array to find the desired element.has()
method, which returns a boolean indicating whether an element with the specified value exists in the set.object[5000]
) to check if an element with the value 5000 exists as a property of the object.has()
method, similar to the set.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and Special JS Features
There are no specific libraries mentioned in the benchmark definition, but sets and maps are built-in JavaScript data structures. Property access (object[5000]
) is also a native feature of JavaScript.
No special JavaScript features are explicitly used in this benchmark. However, if we were to consider more advanced scenarios, features like WeakMap
or Proxy
might be used for specific use cases.
Alternatives
If you're looking for alternatives to these approaches:
Array.prototype.find()
: If searching for the first occurrence of a value in an array.Set.prototype.has()
with a timeout: If performance-critical and using the built-in has()
method is too slow.Object.keys()
or Object.values()
: For iterating through object properties or values, but be aware that these methods can be slower than direct property access.These alternatives might not provide the exact same benefits as the original approaches, but they offer alternative trade-offs and performance characteristics.