記憶體用量 (匿名 RSS + 交換空間)

記憶體用量 (匿名 RSS + 交換空間) 是反映應用程式記憶體用量的指標。

匿名記憶體是指並非由檔案在儲存空間裡支援的記憶體,例如堆積配置和 mmap 配置的記憶體。這項功能會擷取應用程式的動態記憶體配置,包括 Java 或 Kotlin 堆積、未受管理的原生堆積配置 (Bitmap 像素資料位於 Android 8.0 (API 級別 26) 以上版本中),以及執行緒執行堆疊。雖然 OS 可以在壓力下捨棄檔案支援的記憶體,但無法捨棄匿名記憶體。

常駐集大小 (RSS) 是指程序使用的記憶體頁面總數 (包括共用和非共用),這些頁面會保留在實體 RAM 中。如果多個程序 (例如存取相同程式庫的應用程式) 存取某個頁面,該頁面就會視為「共用」。

對於匿名記憶體,系統可以在記憶體不足時,將頁面寫入交換空間 (或 Android 上的 zRAM)。如有需要,系統可以從交換空間讀回這些頁面。

總記憶體用量 (匿名 RSS + 交換空間) 是指應用程式未由儲存空間中的檔案支援的記憶體頁面總數,包括系統在交換空間中保留的任何記憶體。追蹤匿名 RSS + 交換空間,可確保您看到應用程式真實且無法逐出的記憶體用量。

如果應用程式的記憶體用量偏高,請進一步調查並按照本頁面的指南修正問題。

資源

在本機診斷記憶體用量過高的問題

如要開始診斷記憶體用量過高的來源,可以使用開發人員選項中的「記錄記憶體快照資料」Android StudioPerfetto 擷取記憶體快照資料。建議您先測試應用程式的核心使用者歷程,然後在本機擷取堆積傾印。

我們特別建議測試下列使用者歷程:

  • 網頁檢視畫面和應用程式內瀏覽器工作階段
  • 媒體內容豐富的無限捲動網頁
  • 素材資源建立和編輯流程

如要調查潛在的記憶體洩漏問題,請在本地執行相應的使用者歷程,並在不同程序狀態 (可見、前景服務和已快取) 中收集堆積傾印,確認應用程式在進入背景後是否會釋放記憶體。如要瞭解這些程序狀態與 onTrimMemory 回呼的關聯,請參閱為回應事件釋放記憶體的指南。

如果您使用 Android Studio 分析器偵錯記憶體問題,也可以整合 LeakCanary,簡化記憶體流失和重複點陣圖的偵測作業,進而最佳化圖片用量

收集記憶體快照資料後,建議使用 Android 分析器技能分析記憶體快照資料,找出可能導致記憶體用量過高的來源。

以下是 AI 技能可能的回覆內容:

I have completed the analysis of memory leaks and bitmap issues for [app] using the provided Perfetto trace.
  Summary of Findings
  The investigation identified a critical memory pressure issue caused by massive bitmap retention within the app process.
...
Recommendations for [app]
   1. [Library] Image Cache Optimization:
       * Review the [Library] caching strategy. Ensure that bitmaps
         loaded for animations are released or downsampled when the animation is
         not in the foreground.
   2. Asset Resolution Audit:
       * The 14.7 MB average size suggests full-screen or extremely high-density assets. Audit the [library] files in the native_home component to ensure they are not using unnecessarily large source images.
   3. View Lifecycle Management:
       * Investigate why 21 [LibraryImage] instances are alive simultaneously. Ensure that views in the bottom
      tab are properly detached or their animations are cleared when switching between tabs.
   4. Fix Surface Leaks:
       * Address the Surface.release failures observed in the logs, as these can lead to both memory leaks and
         native resource exhaustion.

解讀堆積傾印的其他資源

如要進一步瞭解如何解讀堆積傾印和偵錯記憶體用量,請參閱下列資源:

提升記憶體用量

請參閱下列各節,進一步瞭解如何改善應用程式的記憶體用量:

如需修正記憶體問題的詳細指南,請參閱「管理應用程式的記憶體」指南。