Object Lifecycle
Object Lifecycle
Section titled “Object Lifecycle”Introduction
Section titled “Introduction”Every object in a program goes through a lifecycle: from the moment it’s created (memory allocated) to the moment it’s destroyed (memory reclaimed). Understanding this lifecycle is crucial for writing efficient, leak-free code.
The Object Lifecycle Stages
Section titled “The Object Lifecycle Stages”stateDiagram-v2 [*] --> Declaration: Variable declared Declaration --> Allocation: new keyword Allocation --> Initialization: Constructor called Initialization --> Usage: Object ready Usage --> Unreachable: No more references Unreachable --> GC: Garbage collector runs GC --> [*]: Memory reclaimedStage Details
Section titled “Stage Details”| Stage | What Happens |
|---|---|
| Declaration | Reference variable created (null/undefined) |
| Allocation | Memory allocated on heap |
| Initialization | Constructor runs |
| Usage | Methods called, properties accessed |
| Unreachable | No more references to the object |
| GC | Memory reclaimed (non-deterministic timing) |
Example
Section titled “Example”class Resource { constructor(name) { this.name = name; this.id = ++Resource.instanceCount; } use() { /* using the object */ } dispose() { /* cleanup logic */ }}
// Lifecyclelet res = new Resource("DB Connection"); // Created + Initializedres.use(); // Usedres.dispose(); // Manual cleanupres = null; // Eligible for GCBest Practices
Section titled “Best Practices”- Clean up resources explicitly — close files, connections, sockets
- Don’t rely on finalizers/destructors — they’re not deterministic
- Nullify references to help GC (in long-lived collections)
Previous Topic: Abstract Classes → Next Topic: Memory Management →