Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Memory Life Cycle ใน JavaScript: Allocation, Use, Release

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

  1. Reference Counting: นับ Ref (เก่า, มีปัญหา Cycle)
  2. Mark-Sweep: Trace จาก Root (Standard)
  3. Generational GC (V8): Young/Old Generation
  4. 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