const delayA = time => new Promise(res=>setTimeout(res,time));
const delayT = (func, wait) => {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
var test = function(){
return;
}
(async function(){
await delayA(0);
test();
return;
})();
(async function(){
await delayT(test,0);
return;
})();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
delayA | |
delayT |
Test name | Executions per second |
---|---|
delayA | 73338.4 Ops/sec |
delayT | 74023.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Overview
The benchmark compares two approaches to introduce a delay in asynchronous code execution: await delayA
and delayT
. Both functions are designed to create promises that can be used with async/await
syntax.
Options Compared
The two options being compared are:
await delayA
: This approach uses the new Promise
constructor to create a promise that resolves after a specified time using setTimeout
. The delayA
function returns this promise, which is then awaited in the test code.delayT
: This approach also creates a promise that resolves after a specified time, but it's implemented differently. It uses setTimeout
to schedule a callback function that executes the provided function (test
) with the original arguments.Pros and Cons
Here are some pros and cons of each approach:
await delayA
:delayT
:await delayA
, as it avoids blocking the execution of the code, making it suitable for concurrent and parallel execution.await delayA
.Library
In this benchmark, neither delayA
nor delayT
uses a specific library. However, slice.call
is used in delayT
, which is a part of the ECMAScript standard (section 8.5). This function returns an array-like object from an array or other iterable.
Special JavaScript Features
No special JavaScript features or syntax are being tested in this benchmark.
Benchmark Preparation Code
The provided preparation code defines two functions: delayA
and delayT
. These functions create promises that can be used with async/await
syntax. The test code simply calls these functions with a delay of 0 milliseconds, followed by the test
function, which is an empty function.
Latest Benchmark Result
The benchmark result shows two test runs for each option:
delayT
: 74023.59375 executions per seconddelayA
: 73338.375 executions per secondThis suggests that delayT
outperforms delayA
in terms of execution speed.
Alternatives
If you're interested in alternative approaches to introduce delays in asynchronous code execution, consider:
performance.now()
: Instead of using promises, you can use performance.now()
to get the current timestamp and calculate the delay.Keep in mind that these alternatives might not be as efficient or straightforward as using promises with await
syntax, but they offer different design choices and trade-offs.