Search code examples
javascriptnode.jsperformanceasync-awaitpromise

Why is execution time of this function increasing?


I have following code:

fetchAsync().then()

async function fetchAsync() {
    return await Promise.all([...Array(1000).keys()].map((i) => wait(i)))
}

async function wait(i) {
    const startTime = Date.now();
    await new Promise(resolve => {
        setTimeout(() => resolve(), 100)
    });
    const timePassed = Date.now() - startTime;

    console.log(`Call ${i}: ${timePassed}ms`)
}

Console output is

Call 0: 102ms
Call 1: 108ms 
Call 2: 109ms 
Call 3: 109ms 
Call 4: 109ms 
Call 5: 110ms
...
Call 995: 190ms
Call 996: 190ms
Call 997: 190ms
Call 998: 190ms
Call 999: 190ms

As you can see, the execution time of wait is increasing every time its being executed. Does anyone know why this is happening?


Solution

  • It's because you are calling console.log inside wait. IO is a costly operation and items deeper in your array have to wait for IO for all items occurring before. Use a single console.log to see that each items actually takes the same amount of time -

    fetchAsync().then(console.log) // single console.log
    
    function fetchAsync() {
      return Promise.all(Array.from(Array(1000), (_,i) => wait(i)))
    }
    
    async function wait(i) {
      const startTime = Date.now();
      await new Promise(r => setTimeout(r, 100))
      return `Call ${i}: ${Date.now() - startTime}ms`; // return
    }
    .as-console-wrapper { min-height: 100%; top: 0; }