F
F
floppa3222019-05-01 19:05:58
Node.js
floppa322, 2019-05-01 19:05:58

Why is parallel Promise.all() an order of magnitude slower than sequential awaits?

10 consecutive calls to the database are launched (the sequence means that only 1 worker from the pool is working at any given time).
Then the same number of requests are launched (without waiting for the completion of the previous access to the database), but in this case, not 1, but 10 events should appear in the poll-queue of the Event loop, respectively (in theory) all workers will be loaded.
However, in practice, the 2nd option works more than an order of magnitude slower.

let start = process.hrtime();

    for(let i = 0; i < userIds.length ; i++)
    {
        await User.findOne( { _id: userIds[ i ] } );
    }

    console.log( 'Sequential time through Await: ' + process.hrtime( start ) );


    let findUserTasks = [ ];
    start = process.hrtime();

    for(let i = 0; i < userIds.length ; i++)
    {
        findUserTasks.push( User.findOne( { _id: userIds[ i ] } ) );
    }

    await Promise.all( findUserTasks );

    console.log( 'Parallel time through Promise.all: ' + process.hrtime( start ) );

Output:
Sequential time through Await: 0.22821906
Parallel time through Promise.all: 3.20166249
PS: When slicing images of different sizes using the Sharp module, Promise.all(), as expected, shows itself to be much faster than sequential await 's

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
floppa322, 2019-05-01
@Lite_stream

Found some information: on SO they suggest that the matter may be that Mongo itself behaves a little differently when 1 or more requests are knocked on it per unit of time
Same problem on SO

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question