dart-memory

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Memory Management

内存管理

Mobile devices have limited RAM. Efficient memory management is critical to prevent crashes and ensure a smooth user experience.
移动设备的RAM有限。高效的内存管理对于防止崩溃和确保流畅的用户体验至关重要。

Resource Lifecycle

资源生命周期

  • Explicit Disposal: Always close
    StreamController
    ,
    Timer
    ,
    FocusNode
    , and
    ChangeNotifier
    in the
    dispose()
    method.
  • Late Initialization: Use
    late
    to delay object creation until it's actually needed, reducing initial memory footprint.
  • 显式释放:务必在
    dispose()
    方法中关闭
    StreamController
    Timer
    FocusNode
    ChangeNotifier
  • 延迟初始化:使用
    late
    关键字延迟对象创建,直到实际需要时再初始化,从而减少初始内存占用。

Garbage Collection (GC) Pressure

垃圾回收(GC)压力

  • Generational GC: Dart's GC is optimized for short-lived objects. However, creating thousands of objects in a single frame can still cause jank.
  • Object Re-use: Avoid creating new objects in
    build()
    or high-frequency loops. Reuse data structures where possible.
  • Large Collections: Clearing a large list (
    list.clear()
    ) is better than re-assigning it to a new list if the list itself is long-lived.
  • 分代GC:Dart的GC针对短生命周期对象进行了优化。但在一帧内创建数千个对象仍可能导致卡顿。
  • 对象复用:避免在
    build()
    方法或高频循环中创建新对象。尽可能复用数据结构。
  • 大型集合:如果列表本身是长生命周期的,清空大型列表(
    list.clear()
    )比重新赋值为新列表更好。

Mobile Specifics

移动平台特性

  • Isolates: Use
    Isolate.run()
    for heavy computations (JSON parsing > 1MB, image processing). This keeps the main thread free and prevents UI freezes.
  • Image Memory: Use
    cacheWidth
    and
    cacheHeight
    in
    Image.network
    or
    Image.asset
    to avoid loading high-resolution images into memory at full size.
  • Memory Leaks: Use the DevTools Memory View to identify "leaking" objects that stay in the heap after their context (like a screen) is closed.
  • Isolate:对于繁重计算(解析大于1MB的JSON、图像处理),使用
    Isolate.run()
    。这能让主线程保持空闲,避免UI冻结。
  • 图片内存:在
    Image.network
    Image.asset
    中使用
    cacheWidth
    cacheHeight
    ,避免将高分辨率图片以全尺寸加载到内存中。
  • 内存泄漏:使用DevTools的内存视图来识别在上下文(如某个页面)关闭后仍留在堆中的“泄漏”对象。

Large Data Handling

大型数据处理

  • Pagination: Never load entire datasets into memory. Use server-side or local database pagination (Isar, SQLite).
  • Streaming: For large files or real-time data, use
    Stream
    to process data in chunks rather than buffering the entire content in memory.
  • 分页:切勿将整个数据集加载到内存中。使用服务端或本地数据库分页(Isar、SQLite)。
  • 流式处理:对于大型文件或实时数据,使用
    Stream
    以分块方式处理数据,而非将全部内容缓冲到内存中。