SlideShare a Scribd company logo
▶Garbage Collectors and
Memory Leaks in Node.js V8
Thien Ly - Engineer at Tiki
Tiki Tini App Workshop
Nov 10, 2022
▶ Main Checkpoints
A. 🔥Technical Facts
1. A quick glance at V8
● About V8
● V8’s compiler pipeline
1. About V8 Garbage Collection
● Garbage Collector: ▶ Major GC (Mark-
Compact)
● Garbage Collector: ▶ Minor GC (Scavenger)
● Hidden class
● Inline Cache
● Hot function
1. Best practices with GC
B. 🛡️Practising Memory debugging
1) Profiling frontend app memory with Memlab
framework from Facebook
2) Profiling backend app memory: inspect node
app with Chrome Devtools
A.Technical Facts
1. A quick glance at V8
▶ Garbage Collectors
and Memory Leaks in
Node.js V8
▶A Quick glance at V8
About V8
- “V8 is Google's open source high-performance JavaScript and WebAssembly engine, written in C++.
It is used in Chrome and in Node.js, among others.” (v8.dev)
- Initial release date: Sep 2, 2008
- V8 alternatives:
- SpiderMonkey
- JavaScriptCore(JSC)
- Chakra
- JerryScript
▶A Quick glance at V8
V8’s
compiler pipeline
V8’s compiler pipeline
Source: Franziska Hinkelmann, Ph.D. - Understanding V8’s Bytecode
▶A Quick glance at V8
V8’s compiler pipeline
– Other Resources:
Dig into old versions of V8 compiler pipeline and the Ignition: V8: Hooking up the Ignition to the
Turbofan by Leszek Swirski & Ross McIlroy
A.Technical Facts
2. About V8 Garbage
Collection
▶ Garbage Collectors
and Memory Leaks in
Node.js V8
▶About V8 Garbage Collection
About V8 Garbage Collection
- Stack vs Heap mem
const a1 = 12;
let b1 = a1;
b1 += 1;
const s1 = 'string herer';
const array1 =
[{value:a1},{value:b1}];
▶About V8 Garbage Collection
Stack vs heap mem
- Stack: fixed size; stores static data, includes primitive values like strings, numbers,
boolean, null, and undefined. References that point to objects and functions.
- Heap: stores objects and functions in JavaScript.
“Objects” in this context mean objects in JavaScript, functions, and scopes
> In V8, they divides the heap memory space into 2 regions: young generation and old
generation.
▶About V8 Garbage Collection
Overview of memory management in v8
https://deepu.tech/memory-management-in-v8/
▶About V8 Garbage Collection
Major GC (Full Mark-Compact)
— “The major GC collects garbage from the entire heap.
Marking →Sweeping → Compaction(defragmentation);
- Super slow;
- “Stop the world”;
v8.dev
▶About V8 Garbage Collection
Garbage Collector: ▶ Major GC (Mark-Compact)
Mark ⇒ Sweep ⇒ Compact(defragmentation)
▶About V8 Garbage Collection
Major GC (Full Mark-Compact)
— “The major GC collects garbage from the entire heap.
Marking →Sweeping → Compaction(defragmentation);
- Super slow;
- “Stop the world”;
v8.dev
▶About V8 Garbage Collection
Minor GC (Scavenger)
v8.dev
▶About V8 Garbage Collection
Minor GC (Scavenger)
v8.dev
▶About V8 Garbage Collection
Minor GC (Full Mark-Compact)
- Move mem that is using in heap from A to B
- Compact: re-arrange(just like defrag a hdd)
- Swap A and B, delete the old A ( I mean B now )
- If obj is moved twice, move it to Old generation space for Major GC handle later
v8.dev
▶About V8 Garbage Collection
Hidden Class
- Once object created, V8 also creates a Hidden class to track its props
- Every object shape changes(add/delete object’s properties) create one hidden class
- Support V8 Tracking and Inline Caching
- Objects with the same shape share the same HC
const a1 = {a:2};
const a2 = {a:99};
// a2 and a1 are using the same hidden class
because of their shape.
▶About V8 Garbage Collection
Hidden Class
var obj = {};
obj.x = 1;
obj.y = 2
▶About V8 Garbage Collection
Inline Caching (IC)
- Optimization technique
- Rely on the observation that repeated calls to same function tends
to occur on same type of objects.
- Types:
- Monomorphic (optimized)
- Polymorphic (slightly optimized)
- Megamorphic (unoptimized) // (lv 5 for default, –
max_inlining_levels flag)
▶Best practises and notes
- Limit global variable
- Using short-live object
- Always give name to closures and function -> easy to debug
- Avoid Closures variables:
- Avoid Timer
- Using the dispose pattern, like vscode
- Avoid polymorphism for IC in hot func
// Avoid Closures variables
function clickHandleFactory(){
const eventStore = []; // this never be
collected by gc
return function (event) {
eventStore.push(event);
}
}
const clickHandle = function clickHandleFactory();
button.addEventListener('click',clickHandle);
▶Best practises
- Detached dom checking
B. Practising Memory
debugging
1. Profiling frontend app
memory with Memlab
framework from Facebook
▶ Garbage Collectors
and Memory Leaks in
Node.js V8
▶Profiling FE app memory with Memlab
About Memlab
- Open source by facebook
- Memory testing framework for js
- Under the hood: puppeteer > chrome devtool protocol
Prepare:
- Install memlab with node 16: npm install -g memlab
- Start your own web app
▶Profiling FE app memory with Memlab
Demo
▶Profiling FE app memory with Memlab
Supports Jest testing in Node
Example import type {IHeapSnapshot} from '@memlab/core';
import {config, takeNodeMinimalHeap, tagObject} from '@memlab/core';
function unitToTest(obj){
// example app unit logic
obj.o2 = null;
}
test('should release targeted object', async () => {
config.muteConsole = true;
const owner = {o1:{},o2:{}};
tagObject(owner.o1, 'flag-1');
tagObject(owner.o2, 'flag-2');
unitToTest(owner);
const heap: IHeapSnapshot = await takeNodeMinimalHeap();
expect(heap.hasObjectWithTag('flag-1')).toBe(true);
expect(heap.hasObjectWithTag('flag-2')).toBe(false);
}, 30000);
B. Practising Memory
debugging
2. Profiling BE app memory:
inspect nodejs with chrome
devtool
▶ Garbage Collectors
and Memory Leaks in
Node.js V8
▶Profiling BE app memory: inspect nodejs
with chrome devtool
Demo
▶References and further reads
- Understanding V8's Bytecode - Franziska Hinkelmann, Ph.D., 2017 -
https://www.fhinkel.rocks/posts/Understanding-V8-s-Bytecode;
- Launching Ignition and TurboFan, 2017 - https://v8.dev/blog/launching-ignition-
and-turbofan;
- Trash talk: the Orinoco garbage collector, 2019 - https://v8.dev/blog/trash-talk;
- Leszek Swirski & Ross McIlroy, 2017 - Hooking up the Ignition to the Turbofan by
Leszek Swirski & Ross McIlroy;
- Deepu K Sasidharan - Visualizing memory management in V8 Engine (JavaScript,
NodeJS, Deno, WebAssembly), 2018 - https://deepu.tech/memory-
management-in-v8/;
❯ (Q && A) || SIGTERM
Send your questions via Tiki Developer
Community:
- https://community.tiki.vn/t/building-a-
super-app-workshop-sharing-
garbage-collectors-and-memory-
leaks-in-nodejs-v8/8548
❯ echo 'Gracias ♡ ~' | lolcat

More Related Content

Similar to Garbage collectors and Memory Leaks in Nodejs - V8

It's always sunny with OpenJ9
It's always sunny with OpenJ9It's always sunny with OpenJ9
It's always sunny with OpenJ9
DanHeidinga
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
Yu-Shuan Hsieh
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
guest1f2740
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
Terry Cho
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
Sylvain Wallez
 
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
DataStax
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
DjangoCon2008
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
DjangoCon2008
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
Luiz Fernando Teston
 
Java Performance and Using Java Flight Recorder
Java Performance and Using Java Flight RecorderJava Performance and Using Java Flight Recorder
Java Performance and Using Java Flight Recorder
Isuru Perera
 
Browser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmBrowser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholm
Jameel Nabbo
 
Optimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on Kubernetes
Dinakar Guniguntala
 
G1 collector and tuning and Cassandra
G1 collector and tuning and CassandraG1 collector and tuning and Cassandra
G1 collector and tuning and Cassandra
Chris Lohfink
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentation
Mahmoud Anouti
 
Scaling Django
Scaling DjangoScaling Django
Scaling Django
Mike Malone
 
7 jvm-arguments-v1
7 jvm-arguments-v17 jvm-arguments-v1
7 jvm-arguments-v1
Tier1 app
 
Varnish - PLNOG 4
Varnish - PLNOG 4Varnish - PLNOG 4
Varnish - PLNOG 4
Leszek Urbanski
 
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
Jean-Philippe BEMPEL
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
The World of Smalltalk
 
Master your java_applications_in_kubernetes
Master your java_applications_in_kubernetesMaster your java_applications_in_kubernetes
Master your java_applications_in_kubernetes
Andy Moncsek
 

Similar to Garbage collectors and Memory Leaks in Nodejs - V8 (20)

It's always sunny with OpenJ9
It's always sunny with OpenJ9It's always sunny with OpenJ9
It's always sunny with OpenJ9
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
Lessons Learned on Java Tuning for Our Cassandra Clusters (Carlos Monroy, Kne...
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
Java Performance and Using Java Flight Recorder
Java Performance and Using Java Flight RecorderJava Performance and Using Java Flight Recorder
Java Performance and Using Java Flight Recorder
 
Browser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmBrowser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholm
 
Optimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on Kubernetes
 
G1 collector and tuning and Cassandra
G1 collector and tuning and CassandraG1 collector and tuning and Cassandra
G1 collector and tuning and Cassandra
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentation
 
Scaling Django
Scaling DjangoScaling Django
Scaling Django
 
7 jvm-arguments-v1
7 jvm-arguments-v17 jvm-arguments-v1
7 jvm-arguments-v1
 
Varnish - PLNOG 4
Varnish - PLNOG 4Varnish - PLNOG 4
Varnish - PLNOG 4
 
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
Devoxx Fr 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneu...
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
Master your java_applications_in_kubernetes
Master your java_applications_in_kubernetesMaster your java_applications_in_kubernetes
Master your java_applications_in_kubernetes
 

Recently uploaded

Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 

Recently uploaded (20)

Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 

Garbage collectors and Memory Leaks in Nodejs - V8

  • 1.
  • 2. ▶Garbage Collectors and Memory Leaks in Node.js V8 Thien Ly - Engineer at Tiki Tiki Tini App Workshop Nov 10, 2022
  • 3. ▶ Main Checkpoints A. 🔥Technical Facts 1. A quick glance at V8 ● About V8 ● V8’s compiler pipeline 1. About V8 Garbage Collection ● Garbage Collector: ▶ Major GC (Mark- Compact) ● Garbage Collector: ▶ Minor GC (Scavenger) ● Hidden class ● Inline Cache ● Hot function 1. Best practices with GC B. 🛡️Practising Memory debugging 1) Profiling frontend app memory with Memlab framework from Facebook 2) Profiling backend app memory: inspect node app with Chrome Devtools
  • 4. A.Technical Facts 1. A quick glance at V8 ▶ Garbage Collectors and Memory Leaks in Node.js V8
  • 5. ▶A Quick glance at V8 About V8 - “V8 is Google's open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others.” (v8.dev) - Initial release date: Sep 2, 2008 - V8 alternatives: - SpiderMonkey - JavaScriptCore(JSC) - Chakra - JerryScript
  • 6. ▶A Quick glance at V8 V8’s compiler pipeline V8’s compiler pipeline Source: Franziska Hinkelmann, Ph.D. - Understanding V8’s Bytecode
  • 7. ▶A Quick glance at V8 V8’s compiler pipeline – Other Resources: Dig into old versions of V8 compiler pipeline and the Ignition: V8: Hooking up the Ignition to the Turbofan by Leszek Swirski & Ross McIlroy
  • 8. A.Technical Facts 2. About V8 Garbage Collection ▶ Garbage Collectors and Memory Leaks in Node.js V8
  • 9. ▶About V8 Garbage Collection About V8 Garbage Collection - Stack vs Heap mem const a1 = 12; let b1 = a1; b1 += 1; const s1 = 'string herer'; const array1 = [{value:a1},{value:b1}];
  • 10. ▶About V8 Garbage Collection Stack vs heap mem - Stack: fixed size; stores static data, includes primitive values like strings, numbers, boolean, null, and undefined. References that point to objects and functions. - Heap: stores objects and functions in JavaScript. “Objects” in this context mean objects in JavaScript, functions, and scopes > In V8, they divides the heap memory space into 2 regions: young generation and old generation.
  • 11. ▶About V8 Garbage Collection Overview of memory management in v8 https://deepu.tech/memory-management-in-v8/
  • 12. ▶About V8 Garbage Collection Major GC (Full Mark-Compact) — “The major GC collects garbage from the entire heap. Marking →Sweeping → Compaction(defragmentation); - Super slow; - “Stop the world”; v8.dev
  • 13. ▶About V8 Garbage Collection Garbage Collector: ▶ Major GC (Mark-Compact) Mark ⇒ Sweep ⇒ Compact(defragmentation)
  • 14. ▶About V8 Garbage Collection Major GC (Full Mark-Compact) — “The major GC collects garbage from the entire heap. Marking →Sweeping → Compaction(defragmentation); - Super slow; - “Stop the world”; v8.dev
  • 15. ▶About V8 Garbage Collection Minor GC (Scavenger) v8.dev
  • 16. ▶About V8 Garbage Collection Minor GC (Scavenger) v8.dev
  • 17. ▶About V8 Garbage Collection Minor GC (Full Mark-Compact) - Move mem that is using in heap from A to B - Compact: re-arrange(just like defrag a hdd) - Swap A and B, delete the old A ( I mean B now ) - If obj is moved twice, move it to Old generation space for Major GC handle later v8.dev
  • 18. ▶About V8 Garbage Collection Hidden Class - Once object created, V8 also creates a Hidden class to track its props - Every object shape changes(add/delete object’s properties) create one hidden class - Support V8 Tracking and Inline Caching - Objects with the same shape share the same HC const a1 = {a:2}; const a2 = {a:99}; // a2 and a1 are using the same hidden class because of their shape.
  • 19. ▶About V8 Garbage Collection Hidden Class var obj = {}; obj.x = 1; obj.y = 2
  • 20. ▶About V8 Garbage Collection Inline Caching (IC) - Optimization technique - Rely on the observation that repeated calls to same function tends to occur on same type of objects. - Types: - Monomorphic (optimized) - Polymorphic (slightly optimized) - Megamorphic (unoptimized) // (lv 5 for default, – max_inlining_levels flag)
  • 21. ▶Best practises and notes - Limit global variable - Using short-live object - Always give name to closures and function -> easy to debug - Avoid Closures variables: - Avoid Timer - Using the dispose pattern, like vscode - Avoid polymorphism for IC in hot func // Avoid Closures variables function clickHandleFactory(){ const eventStore = []; // this never be collected by gc return function (event) { eventStore.push(event); } } const clickHandle = function clickHandleFactory(); button.addEventListener('click',clickHandle);
  • 23. B. Practising Memory debugging 1. Profiling frontend app memory with Memlab framework from Facebook ▶ Garbage Collectors and Memory Leaks in Node.js V8
  • 24. ▶Profiling FE app memory with Memlab About Memlab - Open source by facebook - Memory testing framework for js - Under the hood: puppeteer > chrome devtool protocol Prepare: - Install memlab with node 16: npm install -g memlab - Start your own web app
  • 25. ▶Profiling FE app memory with Memlab Demo
  • 26. ▶Profiling FE app memory with Memlab Supports Jest testing in Node Example import type {IHeapSnapshot} from '@memlab/core'; import {config, takeNodeMinimalHeap, tagObject} from '@memlab/core'; function unitToTest(obj){ // example app unit logic obj.o2 = null; } test('should release targeted object', async () => { config.muteConsole = true; const owner = {o1:{},o2:{}}; tagObject(owner.o1, 'flag-1'); tagObject(owner.o2, 'flag-2'); unitToTest(owner); const heap: IHeapSnapshot = await takeNodeMinimalHeap(); expect(heap.hasObjectWithTag('flag-1')).toBe(true); expect(heap.hasObjectWithTag('flag-2')).toBe(false); }, 30000);
  • 27. B. Practising Memory debugging 2. Profiling BE app memory: inspect nodejs with chrome devtool ▶ Garbage Collectors and Memory Leaks in Node.js V8
  • 28. ▶Profiling BE app memory: inspect nodejs with chrome devtool Demo
  • 29. ▶References and further reads - Understanding V8's Bytecode - Franziska Hinkelmann, Ph.D., 2017 - https://www.fhinkel.rocks/posts/Understanding-V8-s-Bytecode; - Launching Ignition and TurboFan, 2017 - https://v8.dev/blog/launching-ignition- and-turbofan; - Trash talk: the Orinoco garbage collector, 2019 - https://v8.dev/blog/trash-talk; - Leszek Swirski & Ross McIlroy, 2017 - Hooking up the Ignition to the Turbofan by Leszek Swirski & Ross McIlroy; - Deepu K Sasidharan - Visualizing memory management in V8 Engine (JavaScript, NodeJS, Deno, WebAssembly), 2018 - https://deepu.tech/memory- management-in-v8/;
  • 30. ❯ (Q && A) || SIGTERM Send your questions via Tiki Developer Community: - https://community.tiki.vn/t/building-a- super-app-workshop-sharing- garbage-collectors-and-memory- leaks-in-nodejs-v8/8548 ❯ echo 'Gracias ♡ ~' | lolcat

Editor's Notes

  1. Intro
  2. Intro