Circular Reference (Tham chiếu vòng)
Xảy ra khi 2 object tham chiếu lẫn nhau (A→B, B→A). Mỗi object có reference count = 1.
- Hệ thống GC thuần túy: không vấn đề nếu không có reference ngoài.
- Hệ thống reference counting: không bao giờ destroy vì count không về 0.
- Hệ thống hybrid: rò rỉ bộ nhớ do không phát hiện được circular reference.
Ví dụ: Circular reference giữa JS object và DOM object
<html> <body> <script> window.onload = function(){ var obj = document.getElementById("DivElement"); document.getElementById("DivElement").expandoProperty = obj; obj.String = new Array(1000).join(new Array(2000)); }; </script> </body> </html>
JS object obj tham chiếu DOM DivElement, DOM có property expandoProperty tham chiếu ngược lại obj → circular reference → memory leak.
Cách khắc phục
Gán null để phá vỡ vòng tròn:
<html> <body> <script> window.onload = function(){ var obj = document.getElementById("DivElement"); document.getElementById("DivElement").expandoProperty = obj; obj.String = new Array(1000).join(new Array(2000)); obj = null; // phá vỡ circular reference }; </script> </body> </html>