var array = [];
var set = new Set();
var map = new Map();
var existingItem1 = {};
var existingItem2 = {};
var existingItem3 = {};
var newItem1 = {};
var newItem2 = {};
var newItem3 = {};
for (let i = 0, item; i < 100; i++) {
item = {index: i};
array.push(item);
set.add(item);
map.set(item, 0);
}
array.push(existingItem1, existingItem2, existingItem3);
set.add(existingItem1); set.add(existingItem2); set.add(existingItem3);
map.set(existingItem1, 0); map.set(existingItem2, 0); map.set(existingItem3, 0);
if (!array.includes(existingItem1)) {
array.push(existingItem1);
}
if (!array.includes(newItem1)) {
array.push(newItem1);
}
if (!array.includes(existingItem2)) {
array.push(existingItem2);
}
if (!array.includes(newItem2)) {
array.push(newItem2);
}
if (!array.includes(existingItem3)) {
array.push(existingItem3);
}
if (!array.includes(newItem3)) {
array.push(newItem3);
}
set.add(existingItem1);
set.add(newItem1);
set.add(existingItem2);
set.add(newItem2);
set.add(existingItem3);
set.add(newItem3);
map.set(existingItem1, 0);
map.set(newItem1, 0);
map.set(existingItem2, 0);
map.set(newItem2, 0);
map.set(existingItem3, 0);
map.set(newItem3, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
conditional array.push | |
set.add | |
map.set overwrite |
Test name | Executions per second |
---|---|
conditional array.push | 10360063.0 Ops/sec |
set.add | 34609856.0 Ops/sec |
map.set overwrite | 32412726.0 Ops/sec |
Let's dive into the benchmark test cases provided.
Benchmark Description
The benchmark is comparing three different methods to add items to a collection: array.push
, set.add
, and map.set
. The test case generates 100 unique items and then adds an additional 3 existing items (existingItem1, existingItem2, existingItem3) to the collection using each of these methods. The benchmark measures how many executions per second each method can handle.
Test Cases
There are three individual test cases:
if
statement to check if an item already exists in the array before pushing it. If it doesn't exist, it's added to the array.add
method.set
method, effectively overwriting any previous value.Library/Feature Used
None of these test cases use any external libraries or special JavaScript features beyond what's built-in to modern browsers (e.g., Sets and Maps).
Options Compared
The benchmark is comparing three different methods:
push
method.add
method to add unique items.set
method to store key-value pairs, effectively allowing overwriting of previous values.Pros/Cons
Here are some pros and cons for each method:
Other Considerations
When choosing an implementation, consider the specific use case:
array.push
may be the way to go.Alternatives
Other alternatives for similar use cases include:
That's it! This explanation should help you understand the benchmark test cases provided.