Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Created December 20, 2023 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syusui-s/4413d7beaec8e2cf9b5eaf20ad3bf22a to your computer and use it in GitHub Desktop.
Save syusui-s/4413d7beaec8e2cf9b5eaf20ad3bf22a to your computer and use it in GitHub Desktop.
{
const sleepZeroMsgChannel = () => {
return new Promise((resolve) => {
const ch = new MessageChannel();
ch.port1.addEventListener('message', () => resolve());
ch.port2.postMessage(0);
ch.port1.start();
});
};
const sleepZeroSetTimeout = () => new Promise((resolve) => setTimeout(resolve, 0));
const time = async (fn) => {
const count = 1000;
let sum = 0;
for (let i = 0; i < count; i++) {
const start = globalThis.performance.now();
await fn();
const end = globalThis.performance.now();
sum = end - start;
}
console.log(fn.name, sum / count, 'ns');
};
time(sleepZeroSetTimeout)
time(sleepZeroMsgChannel)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment