289 字
1 分钟
Dart memory and WeakReferences
2024-08-09

Basic#

Dart uses automatic garbage collection (GC) to manage memory. Here are some key points to remember:

  1. Garbage Collection: When an object is no longer reachable (i.e., there are no references to it), it becomes eligible for garbage collection.

  2. Non-Instant Memory Freeing: Setting a reference to null doesn’t immediately free memory. It only makes the object eligible for GC if there are no other references to it.

SomeClass myObject = SomeClass();
// ... use myObject ...
myObject = null; // Object becomes eligible for GC if no other references exist

Practice#

To optimize memory usage in your Dart applications, consider these practices:

  1. Scope Management: Keep variables in the narrowest scope possible.

  2. Avoid Strong References in callbacks or streams that may outlive the object’s intended lifetime.

  3. Use WeakReferences when appropriate (more on this later).

  4. Implement dispose() methods for large objects or resources:

class ResourceHeavyClass {
  void dispose() {
    // Clean up resources
  }
}
  1. Use const for Compile-Time Constants

  2. Utilize Memory Profiling Tools, especially in Flutter applications.

WeakReferences#

A WeakReference in Dart is a way to refer to an object without preventing that object from being garbage collected. This can be particularly useful in certain scenarios.

Basic Usage#

import 'dart:core';

class SomeClass {}

void main() {
  var object = SomeClass();
  var weakRef = WeakReference(object);
  
  var retrievedObject = weakRef.target;
  if (retrievedObject != null) {
    print('Object still exists');
  } else {
    print('Object has been garbage collected');
  }
}

Key Characteristics#

  • Does not prevent garbage collection of the referenced object.
  • Access the object through the target property.
  • The target property may return null if the object has been collected.

Use Cases#

  1. Caches: Keep objects around if they’re still in use elsewhere, but allow GC if they’re not.
  2. Observers or Event Listeners: Avoid memory leaks in observer patterns.

Limitations#

  • You can’t guarantee when (or if) the garbage collector will run.
  • Not suitable for objects that you always need to keep alive.
Dart memory and WeakReferences
https://blog.lpkt.cn/posts/dart-mem-free/
作者
lollipopkit
发布于
2024-08-09
许可协议
CC BY-NC-SA 4.0