async function foo() {
return 0;
}
async function doit() {
await foo();
}
doit().then(console.log);
function foo() {
return 0;
}
async function doit() {
await foo();
}
doit().then(console.log);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Await on promise | |
Await no promise |
Test name | Executions per second |
---|---|
Await on promise | 193929.2 Ops/sec |
Await no promise | 251098.5 Ops/sec |
I'll break down the provided benchmark and explain what's being tested.
What is being tested?
MeasureThat.net is testing the performance difference between two approaches: using await
with a promise and without it, in this case, with an asynchronous function that returns a value directly (not wrapped in a promise).
Options compared
The two options being compared are:
await
to wait for the completion of a promise returned by another function (foo() -> promise
). The promise is then resolved and the result is logged to the console.await
, but it's applied directly to an asynchronous function that returns a value, bypassing the need for a promise.Pros and Cons of each approach
.catch()
(although not directly applicable here).Other considerations
When using await
with an asynchronous function that returns a value, it's essential to consider how errors will be propagated and handled. In both examples, errors are not explicitly handled, which may lead to unexpected behavior or crashes.
Library usage
In the provided benchmark, no libraries are mentioned as being used. However, if you're using libraries like async/await
polyfills or other utilities that provide a way to work with promises in older browsers, their performance impact should be considered when comparing these approaches.
Special JS feature/syntax
There's no special JS feature or syntax being tested here; the focus is on understanding how await
works in different scenarios. However, if you're interested in exploring other features like async/await, promise chaining, or generators, MeasureThat.net likely has benchmarks for those as well.
Alternatives
If you're looking to compare performance between await
with promises and without them, here are a few alternatives:
then()
instead of await
: This would simulate the behavior of await
on a promise but without the benefits of asynchronous execution.then()
, this approach uses a callback function to handle the result of an asynchronous operation.Promise.resolve()
and then applying the await
keyword.Keep in mind that these alternatives might not accurately represent real-world scenarios, as they don't account for the nuances of asynchronous programming.