maaartinus
maaartinus

Reputation: 46492

Nodejs performance event loop

There are articles claiming superior nodejs performance due to its single threaded event loop. I'm not asking for opinions, I'm asking for a mechanics explanation.

A thread starts to process a request, computes a little, and finds out that it needs to read from a database. This gets done asynchronously. No delay involved and the thread can continue... but what should it do without the data?

A1 makes little sense to me. I can imagine a client issuing other requests in the meantime (like loading multiple resources on first site access), but in general, no.

A2 When it grabs another request, then it loses the whole context. This context gets saved in the promise which will get fulfilled when the data arrive, but which thread does process this promise?

In case B1 you may be lucky and some relevant data may be still in the threads' cache, but given that a DB request takes a few milliseconds, the gain is IMHO low.

Isn't case B2 practically equivalent to a context switch?

Upvotes: 0

Views: 491

Answers (2)

Alexandr Karbivnichyi
Alexandr Karbivnichyi

Reputation: 445

Node.js is based on libuv C library.

Threads are used internally to fake the asynchronous nature of all the system calls. libuv also uses threads to allow you, the application, to perform a task asynchronously that is actually blocking, by spawning a thread and collecting the result when it is done.

A thread starts to process a request, computes a little, and finds out that it needs to read from a database. This gets done asynchronously. No delay involved and the thread can continue... but what should it do without the data?

Pass a callback to a DB module's method, and return from the current function which was invoked as an event listener too. Event loop will continue to next event in a queue. Context is accessible inside callback as function's closure.

Upvotes: 1

SLaks
SLaks

Reputation: 888047

A: Node.js will not respond to any request unless you write code that actively sends a response. It doesn't matter whether that code runs synchronously or asynchronously.
The client (or even the server's networking stack) cannot know or care whether asynchrony happened in the meantime.

B: There is only one Node.js thread, period.
When a response arrives for an asynchronous operation kicked off in Node.js code, an event is raised in the Node.js event loop thread, and the appropriate callback/handler is called.

Upvotes: 0

Related Questions