--- tags: jsdc2021 --- # #Session 4 Memory Leak 與你的距離 {%hackmd 2YoCBdBPTjmHXDr9lEpWuQ %} > 從這開始 > 可以直接打字做共筆囉 :point_down: Kuan@方格子 ![](https://i.imgur.com/CWdHEHp.png) ## Memory Leak 是什麼 - Memory: 儲存各種東東的地方 - 結構 - stack - 我們要有 Release - heap - 新資料 ![](https://i.imgur.com/nHrhMRZ.png) ![](https://i.imgur.com/wSiYH2m.png) ![](https://i.imgur.com/Joqgjjw.png) 使用 Grafana 觀察 ## Outline - Memory Leak 病徵病因 - Garbage Collection in V8 - DevTool ## Memory Leak 病徵病因 ### 複習 Stack and Heap ![](https://i.imgur.com/CR9HcHM.png) - Heap - Code Space: 編譯後的程式碼 (演示) ![](https://i.imgur.com/Z42SHVk.png) - notive 推入 global stack - character 是由 makeWizard 決定 - 呼叫 makeWizard 函式 - 將 name 推到 makeWizard 的 stack - 將 wizard 推到 makeWizard 的 stack - return 傳給呼叫他的人 - character(ptr) 進入 stack - 指向 heap 的 character 值 - 補充:因為 character 很大,而且可能會到處傳(複製開銷大,學 rust 可以幫助了解這些知識) - 若改呼叫 makeWizard ... - wizard 還會存活在 heap 裡面嗎? - wizard 會消失 - who did that? - GC - ![](https://i.imgur.com/Y7PXiqh.png) ## Garbage Collection in V8 ### GC三階段 ![](https://i.imgur.com/DqVFokl.png) - Defragment - Windows 硬碟重組 - SSD 用 TRIM 不要 Defrag! ### Two collectors ![](https://i.imgur.com/dO4taEF.png) https://v8.dev/blog/orinoco-parallel-scavenger - Young Generation - Nursery - 剛出現的新東西 - Intermediate - Old Generation - 比較不需要被清掉 <!-- 記憶體相關領域我不熟 我先聽,先不做共筆喔 --> <!-- OK --> ### Why should GC Generation be existed? ![](https://i.imgur.com/Zj9OMYr.png) ![](https://i.imgur.com/YPocPSp.png) semi-space design from-space and to-space in young ### Major GC ![](https://i.imgur.com/SA1Fnvy.png) Sweep 成本很高,一般V8不會頻繁進行整理,V8判定為 reachable 會保留 反之回收掉 <!-- 是 Defragment 成本高吧 --> ## Find Memory Leak in App 下述有 Memory Leak ![](https://i.imgur.com/43BE1g7.png) 使用 node --inspect 來 Debug 在 DevTools > Memory 使用 k6 進行壓力測試 做之前先進行 snapshot ## 文字版 https://vocus.cc/article/61176c17fd89780001942f1c