2017年3月15日 星期三

[JavaScript]記憶體洩漏(Memory Leak)相關資料整理

整理一下近來蒐集關於JavaScript記憶體洩漏(Memory Leak)相關的資料。

總結JavaScript造成記憶體洩漏的原因就是記憶體參考(這裡有相關說明)。
由於JavaScript採用call by value reference,過程中未處理好不再使用的資料參考,造成資料一直佔據記憶體,最終導致記憶體洩漏。

以下是常見的記憶體洩漏模式:
1. 循環參考
var obj = document.getElementById("someLeakingDIV");
document.getElementById("someLeakingDiv").expandoProperty = obj;
在JavaScript的機制下,DOM與JavaScript因互相參考,導致兩者皆無法被GC回收。

2. 閉包(Closures)
function parentFunction(paramA) {
  var a = paramA;
  function childFunction() {
    return a ++;
  }
  return childFunction();
}
由於閉包的特性,a的變數因childFunction持續被參考,因此a並不會隨著parentFunction的執行結束而消滅,也就是這樣的作法會讓a持續的佔用記憶體。

3. setInterval/setTimeout
setInterval(function(){ /*do something*/ }, 1000);
setTimeout(function(){ /*do something*/ }, 1000);
Timer相關的應用也容易發生,在持續建立新的Timer同樣會占用記憶體,即便該Timer不再使用,因此因善用clearInterval()以及clearTimeout()方法來清理不再使用的Timer。

而關於JavaScript記憶體洩漏的偵錯與監控則可以好好的利用瀏覽器的開發人員工具(以下畫面以Chrome為例)。
1. 錄製記憶體時間線

2. 截取或錄製記憶體資料

這些方法都可以找到特定時間點哪些方法或物件使用了多少記憶體的狀態,方便開發人員抓蟲蟲。

以上是這陣子關於JavaScript記憶體洩漏的簡略整理,感謝收看。

參考資料:
4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them
Find and resolve browser memory leaks caused by JavaScript and Dojo
Fixing Memory Leaks in AngularJS and other JavaScript Applications
JavaScript Tutorial - Memory leaks
JavaScript:Memory Leaks 的情況以及如何解決與偵測
JavaScript 記憶體洩漏(Memory Leak)問題
Memory leak patterns in JavaScript
Walkthrough: Find a memory leak (JavaScript)

沒有留言:

張貼留言