async function asyncFor() {
for (const x of [1, 2, 3]) {
await new Promise(resolve => setTimeout(() => resolve(x > 0), 500));
}
}
async function asyncPromiseAll() {
await Promise.all([1, 2, 3].map(x =>
new Promise(resolve => setTimeout(() => resolve(x > 0), 500))
));
}
asyncFor()
asyncPromiseAll()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
asyncFor | |
asyncPromiseAll |
Test name | Executions per second |
---|---|
asyncFor | 193887.1 Ops/sec |
asyncPromiseAll | 67641.3 Ops/sec |
Benchmark Overview
The provided benchmark compares two approaches for iterating over an array in JavaScript: async/await
with a for...of
loop (asyncFor
) and using Promise.all()
to wait for all promises to resolve (asyncPromiseAll
). The test also includes a delay between iterations to simulate a slower execution.
Options Compared
The benchmark compares two main options:
for...of
loop, which is designed for iterating over arrays, but requires manual handling of promises using new Promise()
. The loop iterates over each element in the array, waiting for 500ms before resolving the promise.Promise.all()
to wait for all promises in an array to resolve. The array is mapped to create new promises, and then Promise.all()
is used to wait for all promises to settle.Pros and Cons of Each Approach
Promise.all()
.Library Used
The benchmark uses the setTimeout()
function, which is a built-in JavaScript library. The new Promise()
constructor also comes from the JavaScript standard library.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark that would require additional explanation. However, note that using await
outside of an async
function is not supported in older browsers and environments without transpilation.
Other Alternatives
Alternative approaches for iterating over arrays include:
for
loops.map()
method, which creates a new array with the results of applying a provided function on every element in this array.Keep in mind that each approach has its own strengths and weaknesses, and the choice ultimately depends on the specific requirements and constraints of your project.