---
# System prepended metadata

title: JavaScript Garbage Collection
tags: [教學]

---

# JavaScript Garbage Collection

## 回收機制
瀏覽器本身會自動GC掉沒有被referenced的記憶體，但某些情況下可能還是會產生memory leak。
可參考: [How JavaScript works: memory management + how to handle 4 common memory leaks](https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec)

除此之外，還有一個情況會產生memory leak:
:::warning
array的重置方式
:::

```
let a = [1,2,3,4];
a = [5,6,7,8]; //memory leak

let a = [1,2,3,4];
a = [];
a = [5,6,7,8]; //memory leak
```
測試執行上述2種code 每跑100萬次記錄一次，記憶體狀況如下圖
![](https://i.imgur.com/0GiRrbM.png)

---
## **正確的釋放方式**
```
let a = [1,2,3,4];
a.length = 0;
a = [5,6,7,8];

let a = [1,2,3,4];
a = null;
a = [5,6,7,8];
```
測試執行上述2種code 每跑100萬次記錄一次，記憶體狀況如下圖
![](https://i.imgur.com/3iiykL2.png)

參考: [JavaScript 深入淺出 Garbage Collection 垃圾回收機制](https://shawnlin0201.github.io/JavaScript/JavaScript-Garbage-Collection/)

---
###### tags: `教學`