-
-
Notifications
You must be signed in to change notification settings - Fork 1
Performances
Thibaut SEVERAC edited this page Aug 4, 2023
·
1 revision
A little point about performances .
looping on decisions can be time consuming, and will block the event loop . So, we choose to be slower, but to unblock the event loop .
Here is an example :
// example 1 a promise containing a loop
const fn = async () => {
console.log('start loop');
console.time('loop');
for (let i = 0; i < 1e5; i++) {
}
console.timeEnd('loop');
}
// we don't await fn
fn();
console.log('do other things');
will log :
start loop
loop: 0.779052734375 ms
do other things
your node app is totally blocked waiting the loop to end
here is another example :
// example 2 a promise containing a loop, calling setImmediate
const fn = async () => {
console.log('start loop');
console.time('loop');
for (let i = 0; i < 1e5; i++) {
await setImmediatePromise();
}
console.timeEnd('loop');
}
//just to call setImmediate in async context
const setImmediatePromise = () => {
return new Promise<void>((resolve) => {
setImmediate(() => resolve());
});
};
// we don't await fn
fn();
console.log('do other things');
will log :
start loop
do other things
loop: 5852.944091796875 ms
yesn the loop is much slower ... but, it doesn't froze your app, and you can do other async things