let counter = 1e5;
const arr = [];
while(counter--) {
for (let i=0; i< 30; i++) {
if (arr.indexOf(i) !== -1) {
arr.push(i);
}
}
}
arr
let counter = 1e5;
const set = new Set();
while(counter--) {
for (let i=0; i < 30; i++) {
set.add(i);
}
}
[set];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Unique | |
Set Unique |
Test name | Executions per second |
---|---|
Array Unique | 73.3 Ops/sec |
Set Unique | 34.6 Ops/sec |
Benchmark Explanation
The provided JSON represents two microbenchmarks that compare the performance of JavaScript arrays with indexOf
method and sets with add
method.
Options Compared:
indexOf
method: In this approach, an array is created and populated with 30 unique elements using a while loop. The indexOf
method is used to check if each element already exists in the array.add
method: In this approach, a Set data structure is created and populated with 30 unique elements using a for loop. The add
method is used to add each element to the set.Pros and Cons:
indexOf
method:indexOf
method is O(n) in the worst case, meaning its performance degrades linearly with the size of the array. This can lead to slower execution times for large datasets.add
method:add
method is O(1) on average, making it much faster than the indexOf
method for large datasets.Library and Syntax Used:
Neither of these benchmarks uses any external libraries. They only rely on built-in JavaScript features.
Special JS Feature or Syntax:
No special JavaScript feature or syntax is used in these benchmarks. The code follows standard JavaScript syntax and conventions.
Other Alternatives:
Map
data structure: Instead of arrays, you could use a Map data structure to store the elements. Maps are designed for storing key-value pairs and can provide faster lookups than arrays with the indexOf
method.Here's a sample implementation of the two benchmarks in JavaScript:
// Array with indexOf method
function arrayBenchmark() {
const counter = 1e5;
const arr = [];
while (counter--) {
for (let i = 0; i < 30; i++) {
if (arr.indexOf(i) !== -1) {
// do nothing
} else {
arr.push(i);
}
}
}
}
// Set with add method
function setBenchmark() {
const counter = 1e5;
const set = new Set();
while (counter--) {
for (let i = 0; i < 30; i++) {
set.add(i);
}
}
return [...set];
}
Note that the setBenchmark
function returns an array from the set, as the benchmark is designed to compare the two approaches.