# Memory Optimization

# 1. Use subcontract loading reasonably

Using sub-package to load not only optimizes startup time, but also enables a more coarse-grained on-demand load of pages, components, and logic, reducing memory usage.For details, please refer to < Startup Optimization - Code Package Volume Optimization >

# 2. Use on-demand injection and time-use injection

By turning on on-demand injection and on-time injection, you can avoid loading unused pages and components at runtime and reduce memory usage at runtime.For details, please refer to < Startup Optimization - Code Injection Optimization >

# 3. Memory analysis

If you want to analyze the memory distribution of the Weixin Mini Program logical layer more finely,You can use the Developer Tools Debugger's Memory Debugging "or the" Memory Debugging capabilities provided by Debugger 2.0.

# 4. Handling memory alerts

When Weixin Mini Program takes up too much system resources, it may be destroyed by the system or recovered by WeChat. On iOS, when the WeChat client receives a system memory alert for a certain period of time, it actively destroys the Mini Program according to a strategy and prompts the user to "run insufficient memory, please reopen the Mini Program."

It is recommended that Weixin Mini Program use wx.onMemoryWarning to listen for memory alarm events when necessary and perform necessary internal cleanup.For example, release some temporarily unused components or JS objects.

# 5. Weixin Mini Program Common Internal Storage Leak Problems

The existence of a memory leak problem will cause Weixin Mini Program to continue to increase the memory footprint during the run process, causing the Mini Program to flash back or be forcibly destroyed by WeChat.

# 5.1 Weixin Mini Program Holding page instances for a long time, resulting in page instances and referenced components cannot be destroyed normally

After the page is unloaded, the base library cleans the page instance from the page stack. Under normal circumstances, the JS recycling mechanism will recycle the page and free up memory.

But if the page instance held in developer code (this)Failing to release causes the page to not be recycled properly, causing a memory leak. Developers are advised to pay attention and do the necessary cleanup in unload.

Case 1: Page instances are listened to by unbundled events

This of the page is held in the event monitor, and if the page is destroyed and the listener is not unbound, the page cannot be released.

Page({
  themeChangeHandler({ theme }) {
    this.setData({ theme })
  },
  onLoad() {
    this._handler = this.themeChangeHandler.bind(this)
    wx.onThemeChange(this._handler)
  },
  // 修复方法:unload 中解绑监听
  // onUnload() {
  //   wx.offThemeChange(this._handler)
  // },
})

Case 2: A page instance is referenced by an extra-page variable or a global variable

The function closure holds the page's this, and the function is hung to a variable that is global or outside the page's declaration cycle, causing the page to not be released.

let languageListener = null

Page({
  onLoad() {
    getApp().userInfoChangeListener = ({ userName }) => {
      this.setData({ userName })
    }
    languageListener = ({ lang }) => {
      this.setData({ lang })
    }
  },
  // 修复方法:unload 中进行清理
  // onUnload() {
  //   getApp().userInfoChangeListener = null
  //   languageListener = null
  // },
})

Case 3: A page instance being asynchronously called back for a long time

If this of a page is accessed in an asynchronous callback that has not returned for a long time, such as asetTimeoutsetInterval,A long wxAPI callback (such as a longwx.request, etc.) will result in a page not being released.

Page({
  onLoad() {
    this._timer = setInterval(() => {
      this.setData({
        timerValue: Date.now()
      })
    }, 1000)
  },
  // 修复方法:unload 中进行清理
  // onUnload() {
  //   clearInterval(this._timer)
  // },
})

# 5.2 Incident listening was not untied in time

After the incident listening, the listener should be unfastened in time.

const locationChangeListener = function (res) {
  console.log('location change', res)
}
wx.onLocationChange(locationChangeListener)
wx.startLocationUpdate()
// After the listening is over
wx.stopLocationUpdate()
// How to fix it: Unplug the listening when not in use
// wx.offLocationChange(locationChangeListener)

# 5.3 未清理的定时器

开发者在开发如「秒杀倒计时」等功能时,可能会使用 setInterval 设置定时器,页面或组件销毁前,需要调用 clearInterval 方法取消定时器。