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();
})();
(async function(){
delayT(test,0);
})();
(async function(){
setTimeout(test,0);
})();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
delayA | |
delayT | |
setTimeout |
Test name | Executions per second |
---|---|
delayA | 42550.0 Ops/sec |
delayT | 40266.6 Ops/sec |
setTimeout | 69871.4 Ops/sec |
I'd be happy to explain the JavaScript benchmark on MeasureThat.net.
Overview
The benchmark tests three approaches for introducing delays in asynchronous code: await delayA
, delayT
(a wrapper around setTimeout
), and setTimeout
directly.
Options Compared
await delayA
: This approach uses a custom promise-based delay function, delayA
. It returns a promise that resolves after the specified time.delayT
: This is a modified version of setTimeout
, which wraps its arguments in an array and applies them to a new function with the original timeout value. The main difference is that it uses apply()
instead of passing arguments directly, as shown in the benchmark code.setTimeout
: A direct call to the native setTimeout
function.Pros and Cons
await delayA
:setTimeout
directly.setTimeout
.delayT
:setTimeout
, which can be useful in certain scenarios. It's also a simple and straightforward approach.apply()
might incur additional overhead, making it slightly slower than await delayA
or native setTimeout
.setTimeout
:Library and Special JS Features
The test uses no external libraries or special JavaScript features (such as Web Workers or async/await polyfills). The custom delayA
function is used only within the benchmark code, not in any production environment.
Other Alternatives
Some alternative approaches for introducing delays could include:
Promise.then()
instead of promises or native setTimeout
.setImmediate()
function.