const numbers = Array(10).fill(Array.from({ length: 100000 }, (_, i) => i + 1)).flat();
const a = [];
for (const number of numbers) {
a.push(number);
}
const s = new Set();
for (const number of numbers) {
s.add(number);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.push() | |
Set.add() |
Test name | Executions per second |
---|---|
array.push() | 190.6 Ops/sec |
Set.add() | 42.7 Ops/sec |
In this benchmark, we are comparing two different methods for populating a collection in JavaScript: using the Array.prototype.push()
method on an array versus using the Set.prototype.add()
method to populate a Set.
Data Preparation:
The benchmark preparation code initializes an array called numbers
, which contains numbers from 1 to 100,000. This data structure serves as the input for both test cases.
array.push()
push()
method adds one or more elements to the end of an array and returns the new length of the array.a
, then iterates through the numbers
array using a for-of loop, pushing each number into a
.Set.add()
add()
method adds a new element to a Set object, which can hold only unique values.s
and iterates through the numbers
array, using add()
to include each number.According to the benchmark results:
array.push()
operation executed approximately 94.65 times per second.Set.add()
operation executed around 52.30 times per second.From this data, we observe that array.push()
outperforms Set.add()
in this particular case. This is likely due to the simplicity of appending elements to an array compared to looking up and inserting into a Set, which is inherently more complex because it checks for uniqueness.
In conclusion, the benchmark examines the efficiency of two collection types in handling data insertion, highlighting their unique advantages and disadvantages while presenting performance metrics that inform implementation decisions.