var data = [new Array(100)].map((_, i) => i);
var checkedPush = (array, item) => {
for (let i = 0, len = array.length; i < len; ++i) {
let isPresent = false;
for (const oldItem of array) {
if (oldItem === item) {
isPresent = true;
break;
}
}
if (!isPresent) {
array.push(item);
}
}
}
var smallSet = new Set();
for (const item of data) {
smallSet.add(item);
}
var smallArray = [];
for (const item of data) {
checkedPush(data, item);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Checked array |
Test name | Executions per second |
---|---|
Set | 490191.9 Ops/sec |
Checked array | 944.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for adding elements to an array: using a Set
data structure (Option 1) versus checking if an element already exists in the array before adding it (Option 2). The goal is to determine which approach is faster.
Test Cases
There are two individual test cases:
Set
data structure to add all elements from the data
array to a new set. A Set
in JavaScript is an unordered collection of unique values.checkedPush
function to check if each element already exists in the data
array before adding it to the array.Options Compared
The benchmark compares two options:
Other Considerations
When choosing between these two options, consider the following factors:
Set
data structure might be a better choice.Library Used
In the benchmark code, the checkedPush
function uses a library called Lodash (not explicitly mentioned in the provided JSON). The checkedPush
function is a custom implementation that checks for duplicates before adding an element to the array. Lodash is a popular JavaScript utility library providing functional programming helpers and iterables.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark. However, it's worth noting that using Set
data structures and custom functions like checkedPush
might require some familiarity with modern JavaScript features, such as first-class functions and iterable objects.
Now, let's look at the latest benchmark results:
The results show that using a Set
data structure (Option 1) is significantly faster than using the checked array approach (Option 2). The Safari 15 browser on Mac OS X 10.15.7 achieved an average execution time of around 100-150 ns for the Set test case, while the checked array test case took around 200-250 ns.
As for alternatives, some other approaches to adding elements to an array include:
Array.prototype.includes()
and push()
: This method would require checking if each element already exists in the array before adding it, which is similar to Option 2.These alternatives are not mentioned in the provided benchmark code and would require further exploration for comparison.