# 了解 JavaScript 記憶體管理來調整效能與畫面入門
## Ted
---
## Speaker
### Ted Shiu
### 第一網站 前端工程師
### [Github](https://github.com/tedshd)
---
## Intro
在現今的硬體裝置都有強大的效能下
不少關於記憶體的掌控經常被前端工程師忽視
但基本上在做程式開發記憶體管理是很重要的一環
假如有認識一些開發 APP 的工程師跟他們聊天就常常會聽到他們抱怨說有時 code 沒寫好造成記憶體溢位, 或 APP 分配記憶體的不足造成 APP 閃退
當然在 web 很難遇到這件事
但當電腦或手機的記憶體不足時, 這個網頁的 process 所耗的記憶體又爆掉了
----
![](https://i.imgur.com/aJAXJDj.png)
在 chrome 上就會出現這個...
---
## Memory Management
1. 分配需要的記憶體
2. 使用分配出來的記憶體
3. 當不使用時, 釋放掉分配的記憶體
JavaScript 在這部分是由各個 Browser 的 JavaScript 解譯器處理的, 所以不會有具體的處理方式
---
### 分配需要的記憶體
```JavaScript
var n = 123; // allocates memory for a number
var s = 'azerty'; // allocates memory for a string
var o = {
a: 1,
b: null
}; // allocates memory for an object and contained values
// (like object) allocates memory for the array and
// contained values
var a = [1, null, 'abra'];
function f(a) {
return a + 2;
} // allocates a function (which is a callable object)
// function expressions also allocate an object
someElement.addEventListener('click', function() {
someElement.style.backgroundColor = 'blue';
}, false);
```
---
### 使用分配出來的記憶體
用就對了
但要注意所謂的
`call by value`
`call by reference`
`javascript deep clone`
[demo](http://jsbin.com/wazedixavo/edit?html,js,console,output)
[demo 2](https://tedshd.io/demo/javascript_value_demo.html)
---
### 當不使用時, 釋放掉分配的記憶體
經常出問題的關鍵點
Developer 需控管記憶體的分配
高階語言具有 garbage collector 機制
----
#### garbage collector(GC) 機制
1. Reference-counting garbage collection
2. Mark-and-sweep algorithm
----
#### Reference-counting garbage collection
By reference 計算
無 reference 時 GC
缺點
互相 By reference 進入死循環會造成無法 GC
```JavaScript
function f() {
var o = {};
var o2 = {};
o.a = o2; // o references o2
o2.a = o; // o2 references o
return 'azerty';
}
f();
```
----
#### Mark-and-sweep algorithm
從 root 開始掃描標記
不可到達 root 便進入 GC
----
#### 手動處理
一般來說不必這樣做了
```JavaScript
var obj = {
str: 'text',
run: function () {
console.log('this is run');
}
};
delete obj.run;
obj.str = null;
```
---
## Experience
[menu_list](https://github.com/tedshd/menu_list)
[slider_preview](https://github.com/tedshd/slider_preview)
[amp-carousel](http://tedshd.github.io/slider_preview/)
[Chrome DevTools Overview](https://developer.chrome.com/devtools)
[Profiling memory performance](https://developer.chrome.com/devtools/docs/heap-profiling)
---
## Reference
[Memory Management - JavaScript | MDN](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Memory_Management)
[Tracing garbage collection - Wikipedia](https://en.wikipedia.org/wiki/Tracing_garbage_collection)
{"metaMigratedAt":"2023-06-14T13:00:49.298Z","metaMigratedFrom":"Content","title":"了解 JavaScript 記憶體管理來調整效能與畫面入門","breaks":"true","contributors":"[]"}