Basic
Dart uses automatic garbage collection (GC) to manage memory. Here are some key points to remember:
-
Garbage Collection: When an object is no longer reachable (i.e., there are no references to it), it becomes eligible for garbage collection.
-
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:
-
Scope Management: Keep variables in the narrowest scope possible.
-
Avoid Strong References in callbacks or streams that may outlive the object’s intended lifetime.
-
Use WeakReferences when appropriate (more on this later).
-
Implement
dispose()
methods for large objects or resources:
class ResourceHeavyClass {
void dispose() {
// Clean up resources
}
}
-
Use
const
for Compile-Time Constants -
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
- Caches: Keep objects around if they’re still in use elsewhere, but allow GC if they’re not.
- 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.