Memory Life Cycle (วัฏจักรหน่วยความจำ)
ทุกภาษา มี 3 ขั้นตอน แต่ High-level Language (JS) จัดการ Auto
1. Allocation (จัดสรรหน่วยความจำ)
JavaScript = Garbage Collected Language ประกาศตัวแปร = Allocate Auto
var n = 989; // Number
var s = 'qwerty'; // String
var o = { a: 1, b: null }; // Object + contained values
var a = [1, 2, 3]; // Array
var fn = () => {}; // Function
2. Use (ใช้งานหน่วยความจำ)
Read/Write Variable, Property, Pass Argument, Call Function
console.log(n); // Read
o.a = 2; // Write
fn(o); // Pass Reference
arr.push(4); // Mutate
3. Release (ปล่อยหน่วยความจำ)
หา Object ที่ Unreachable จาก Root → GC Collect
- Variable Out of Scope
- Reference ถูก Overwrite/Delete
- WeakRef/WeakMap ไม่นับเป็น Strong Reference
Garbage Collector Algorithms
- Reference Counting: นับ Ref (เก่า, มีปัญหา Cycle)
- Mark-Sweep: Trace จาก Root (Standard)
- Generational GC (V8): Young/Old Generation
- Incremental/Concurrent: แบ่งงาน GC เพื่อไม่ Block Main Thread
Undecidable Problem
General Problem: "Memory นี้ยังต้องใช้ไหม?" = Undecidable (Halting Problem) GC ใช้ Heuristics/Estimation
Best Practices สำหรับ Dev
- Limit Scope (Block Scope ด้วย let/const)
- Nullify References เมื่อไม่ใช้ (ค่าใหญ่, DOM, Timers)
- หลีกเลี่ยง Global Variables
- ใช้ WeakMap/WeakSet สำหรับ Cache/Metadata
- Monitor ด้วย DevTools Memory Tab