function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
var a = shuffle(Array(100000).fill(undefined).map((_, i) => i));
var b = a.reduce((acc, el) => { acc[el] = true; return acc }, {});
var c = new Set(a);
var d = new Map(a.map(el => [el, true]));
var elements = [1, 100, 1000, 24, 56, 78, 23, 5643, 863, 2679, 9999, 45, 5832, 7510, 3756];
return elements.map(el => a.includes(el))
return elements.map(el => b[el])
return elements.map(el => c.has(el))
return elements.map(el => d.get(el))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
hash | |
set | |
map |
Test name | Executions per second |
---|---|
includes | 1118.2 Ops/sec |
hash | 881811.9 Ops/sec |
set | 776648.6 Ops/sec |
map | 750669.1 Ops/sec |
Let's break down the provided JSON and explain what is tested on the website, along with the pros and cons of different approaches.
Benchmark Definition
The benchmark defines four test cases:
set.has
array.includes
obj[key]
(assuming an object a
created using the shuffle
function)map.get
These tests compare the performance of four different data structures and methods to check for membership in a list: Sets, arrays, objects, and Maps.
Data Structures and Methods
Here's what each test case checks:
set.has
: Checks if an element is present in a Set.array.includes
: Checks if an element is present in an array using the includes
method.obj[key]
: Checks if an element is present in an object by accessing its key-value pair using bracket notation (obj[key]
). (Note: This assumes that the object a
has been shuffled and populated with unique elements.)map.get
: Checks if an element is present in a Map.Options Compared
The benchmark compares the performance of these four approaches:
includes
method is used for membership testing.obj[key]
) is used to access elements by their keys.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
includes
method's implementation.Library and Special Features
The benchmark uses the shuffle
function from the Lodash library to shuffle an array of unique elements. It also assumes that the object a
has been created using this shuffled array.
No special features or syntax are used in this benchmark.
Alternatives
If you're looking for alternatives to these approaches, consider:
Set
data structure instead of an array for fast membership testing.includes
method on arrays or objects for better performance.Keep in mind that the choice of approach depends on your specific use case and requirements.