const set = new Set();
for (let i = 0; i < 10000; ++i) {
set.add(`key_${i}`);
}
for (let j = 0; j < 10000; ++j) {
set.add(`key_${j}`);
}
let result = 0;
for (let k = 0; k < 20000; ++k) {
result += set.has(`key_${k}`);
}
console.log(result);
const obj = {};
for (let i = 0; i < 10000; ++i) {
obj[`key_${i}`] = true;
}
for (let j = 0; j < 10000; ++j) {
obj[`key_${j}`] = 1;
}
let result = 0;
for (let k = 0; k < 20000; ++k) {
result += obj.hasOwnProperty(`key_${k}`);
}
console.log(result);
const map = new Map();
for (let i = 0; i < 10000; ++i) {
map.set(`key_${i}`, true);
}
for (let j = 0; j < 10000; ++j) {
map.set(`key_${j}`, 1);
}
let result = 0;
for (let k = 0; k < 20000; ++k) {
result += map.get(`key_${k}`);
}
console.log(result);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Object | |
Map |
Test name | Executions per second |
---|---|
Set | 471.4 Ops/sec |
Object | 332.8 Ops/sec |
Map | 450.0 Ops/sec |
Let's break down what's being tested in the provided benchmark.
The benchmark is comparing three data structures: Sets, Objects, and Maps. Each test case uses a different data structure to perform a specific operation:
Set
object to store keys and check if they exist using the has()
method.{}
) to store key-value pairs, where each value is either true
or a numeric value (1
). It then checks if a key exists using the hasOwnProperty()
method.Map
object to store keys and values, where each value is associated with a string value (true
or '1'
). It then retrieves the value associated with a key using the get()
method.Options being compared:
has()
in Sets, hasOwnProperty()
in Objects).in
operator or property names.Pros and Cons of each approach:
Library and purpose:
The Map
data structure is a built-in part of modern JavaScript (since ECMAScript 2015), while Objects are also native to JavaScript. The use of these data structures depends on the specific requirements of your application and personal preference.
Special JS features or syntax:
None mentioned in this benchmark, but note that this benchmark uses ES6+ features like arrow functions (=>
), template literals (\r\n
), and const
declarations.
Other alternatives: If you need to compare performance with other data structures, consider using:
This benchmark is focused on comparing the performance of different data structures in JavaScript for a common use case (existence checks).