Garbage Collection in Dart

Garbage Collection in Dart

About

  • Garbage Collection automatically manages memory allocation/reclamation.
  • Dart uses generational GC with young/old space.
  • No stop-the-world pauses (incremental marking/concurrent sweeping).
  • Each isolate has its own heap.

Main Topics

  1. Generational Collection

    • Definition: Young space (frequent collections) vs old space (less frequent).
    • Example:
      void createObjects() {
        // Allocated in young space
        var temp = List.filled(1000, 'data');
      } // Collected quickly if unreachable
  2. Mark-Sweep Algorithm

    • Definition: Identifies and removes unreachable objects.
    • Example:
      var object1 = Object();
      var object2 = Object();
      object1 = null; // Now eligible for GC
  3. Memory Allocation

    • Definition: How Dart allocates objects.
    • Example:
      // Small objects in young space
      final point = Point(10, 20);
      // Large objects directly in old space
      final buffer = Uint8List(1000000);
  4. GC Triggers

    • Definition: Conditions that initiate collection.
    • Example:
      // Common triggers:
      // - Young space full
      // - Old space growth threshold
      // - Manual invocation (rarely needed)
  5. Isolate Memory

    • Definition: Independent heaps per isolate.
    • Example:
      // No shared memory between isolates
      // Communication via message passing

How to Use

  • Best Practices: Avoid premature optimization
  • Monitoring: Use DevTools Memory tab
  • Large Data: Consider isolates for heavy processing
  • Leak Detection: Watch for growing memory charts

How It Works

  1. Allocation: Objects created in young space
  2. Promotion: Surviving objects move to old space
  3. Marking: Traces object references
  4. Sweeping: Reclaims unreachable memory
  5. Compacting: (Occasionally) reduces fragmentation

Example Memory Profile:

void main() {
  // Profile this in DevTools:
  List<List<int>> matrix = [];
  for (int i = 0; i < 1000; i++) {
    matrix.add(List.filled(1000, i));
  }
}

Conclusion

Dart’s garbage collector provides automatic memory management through efficient generational collection, enabling developers to focus on application logic rather than manual memory management. Its isolate-specific heaps and concurrent operations ensure smooth performance without blocking the main execution thread.