SlideShare a Scribd company logo
1 of 30
▶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 OpenJ9DanHeidinga
 
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 GoYu-Shuan Hsieh
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunningguest1f2740
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance TunningTerry 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 1DjangoCon2008
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance DjangoDjangoCon2008
 
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 RecorderIsuru Perera
 
Browser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmBrowser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmJameel Nabbo
 
Optimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesDinakar Guniguntala
 
G1 collector and tuning and Cassandra
G1 collector and tuning and CassandraG1 collector and tuning and Cassandra
G1 collector and tuning and CassandraChris Lohfink
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentationMahmoud Anouti
 
7 jvm-arguments-v1
7 jvm-arguments-v17 jvm-arguments-v1
7 jvm-arguments-v1Tier1 app
 
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
 
Master your java_applications_in_kubernetes
Master your java_applications_in_kubernetesMaster your java_applications_in_kubernetes
Master your java_applications_in_kubernetesAndy 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

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

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