var set1 = new Set();
var count = 1000;
for(var i = 0; i<count; i++)
{
set1.add(i);
}
for (const contentId of set1) {
set1.has(contentId);
}
function setTest(contentId){
set1.has(contentId);
}
set1.forEach(setTest)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach |
Test name | Executions per second |
---|---|
for | 13711.5 Ops/sec |
foreach | 13404.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to measure the performance of two different approaches for iterating over a Set data structure in JavaScript:
for
loop to iterate over the elements of the Set.forEach
method provided by the Set interface to iterate over its elements.What's being tested?
The benchmark is testing the following aspects:
Options compared
Two options are being compared:
for
loop: This is a manual, iterative approach that uses an index variable (i
) to iterate over the elements of the Set.forEach
method: This is a built-in method provided by the Set interface that allows you to iterate over its elements without manually keeping track of an index.Pros and Cons
Here are some pros and cons for each approach:
Traditional for
loop
Pros:
Cons:
forEach
.forEach
method
Pros:
forEach
are optimized for performance and usually faster.Cons:
forEach
method on Sets; this might not be an issue for modern browsers but could be important for older or less common ones.Library and syntax
No specific library is used in these benchmark tests. The Set data structure and its methods (like has
and forEach
) are part of the standard JavaScript API.
Special JS feature or syntax
There's no special JS feature or syntax being used here, other than the built-in forEach
method on Sets. No experimental features like async/await or new array methods (e.g., map
, filter
, reduce
) are employed.
Other alternatives
If you wanted to test alternative approaches for iterating over a Set, some examples could include:
next()
function or iteratorKeep in mind that these alternatives would likely have different performance characteristics and might not be as efficient as using built-in methods like forEach
.
The provided benchmark tests the performance of two established approaches for iterating over Sets: traditional manual iteration (for
loop) versus the optimized, built-in forEach
method. By comparing execution times across different browsers and devices, this benchmark helps identify performance differences and provides insights into how to optimize Set-based code in JavaScript.