DEV Community

Discussion on: Is Node.js Single-Threaded or Multi-Threaded? and Why?

Collapse
 
metcoder profile image
Carlos Fuentes

Hi @arealesramirez great article!
I would like to complement with the following:

  • JavaScript is not > Java in terms of the speed. It can in fact be more performant in terms of memory footprint, and even at some point speed, but it requires for the app to run for a time while the hot paths are being identified for optimization by V8 engine. On the other hand, Java already mades optimizations ahead of time because it optimizes during compilation, kinda the same happens with C# (typical thing between an Interpreted and a Compiled language).
  • Node.js doesn't have a single thread, in fact the JS code is executed on a single thread, you're right, but the I/O interaction happens within a thread-pool handled by libuv. This means that the Node.js process itself spawns more than one thread, but your JS code will run on a single thread thanks to V8.
  • About Worker_Threads, you're right, it spawns a V8 vm instance for executing the JS code, but have in mind that is not the same as the Cluster module, they will share the same Event Loop, and for instance the same thread-pool (libuv). Remember that the Event Loop is not within V8 engine, but rather within Libuv. Each browser has it's own Even Loop + VM engine for executing JS code. e.g. Deno uses V8 + Tokio Event engine.

Nice work! Keep it going :)

Collapse
 
coen_c7a57bc84f2f2 profile image
Coen de Wit

Please use the correct facts when referencing other environments like C# (and probably Java too on that topic). With dotnet (C#) you can choose to use AOT compilation when optimizing for startup time. But default it compiles to byte-code which during runtime is JIT compiled in multiple tiers, optimizing during the lifetime. It is even possible to create a profile from test runs to optimise before runtime.

Collapse
 
arealesramirez profile image
Andres Reales

Thanks for complementing.

As per my understanding, worker_threads will share memory but each will have each own independent event loop.

Collapse
 
metcoder profile image
Carlos Fuentes

Kinda, the worker thread can share memory with other threads (made out of the same parent thread) or the parent thread itself. But they just create a new instance of the V8 engine, not another full Node process (where the Node process is who instantiate the event_loop). In Contrast, Cluster in fact instantiates one or more new Node process, for instance they come with it's own event_loop :)

Thread Thread
 
arealesramirez profile image
Andres Reales

Oh yeah! I see what you mean. Using pm2 is a good implementation of clusters where we could have a node per each core of the cpu.
Thanks for the clarifying about the event loop!

Thread Thread
 
metcoder profile image
Carlos Fuentes

Exactly! 😄
No worries, happy to help! As I said, great work ;)