NodeJS Event Loop: a lean concept review

NodeJS Event Loop: a lean concept review

Summary:

  1. Introduction
  2. Heap and stack memory
  3. How does event loop actually work?
  4. Practical example
  5. Related problems
  6. Conclusion and video recommendation


1. Introduction

NodeJS is a single-threaded language. That is, only one task is executed at a time.

Efficiency is not a problem at all given the event loop approach, which we’re going to take a look today.


First of all, let’s review two important concepts:

2. Heap and stack memory

Heap: Memory space to storage objects and dynamic data.

Stack (LIFO): Memory space that refers to function calls and primary variables.

function example() {
	let x = 10; // Stack
	let object = { valor: 20 }; // Heap
}
exemplo(); // Referred in stack        

3. How does event loop actually work?

It manages async operations and keep a non-blocking behavior.

It interacts with the “Call Stack”, “Callback queue”, “Microtask queue” and "Node API".

  1. Every synchronous code is executed in the Call Stack.
  2. Asynchronous calls are sent to Node API.
  3. Callbacks returns to Callback Queue or Microtask Queue (in case of Promises).
  4. Event loop processes the Microtask / Callback Queue when the Call Stack is empty.



4. Practical example

console.log("1");

setTimeout(() => {
    console.log("2");
}, 0);

Promise.resolve().then(() => console.log("3"));

console.log("4");        

  1. “1” and “4” are printed immediately, once they’re synchronous calls.
  2. setTimeout call goes to the callback queue after being processed by Node API.
  3. The promise goes to the microtask queue after being processed by Node API.
  4. “3” is printed before “2”, once the microtask queue has a higher priority.


5. Related problems

Stack overflow: occurs when recursive functions grows non-stop, filling up the call stack, which blocks the execution.

function nonStopRecursive() {
    return nonStopRecursive(); // Never stops, fills up the Call Stack 
}
nonStopRecursive();        

Memory leak: occurs when object references are not released.

let list = [];
setInterval(() => {
    list.push(new Array(1000000).fill("leak")); // Never releases the memory.
}, 1000);        

Blocking code: once Node is single-threaded, long synchronous operations blocks the event loop execution, which blocks other the execution of other tasks.

const fs = require("fs");

// Reads a large file in a blocking approach
const data = fs.readFileSync("large_file.txt");
console.log("File loaded"); // NodeJS blocks until the file is read.        

6. Conclusion

At the end of the day, event loop is a core mechanism behind the asynchronous and non-blocking NodeJS architecture.

This is what makes the application efficient and allows you to run parallel operations (even though it's not truly multi-thread).

Understanding its behavior is crucial to avoid issues such as Stack Overflow, Memory Leaks and Blocking Code. Not only that, but it's also important to remember the processing priority between the Microtask and Callback queues.

I highly recommend watching: https://www.youtube.com/watch?v=8aGhZQkoFbQ

要查看或添加评论,请登录

Daniel Domingueti的更多文章

社区洞察

其他会员也浏览了