# Memory optimization

# 1. Reasonable use of subcontract loading

useSubcontract loadingIt not only optimizes startup time, but also enables coarse-grained on-demand loading of pages, components, and logic, thereby reducing memory footprint. For details, please refer toStartup Optimization - Code Package Volume Optimization

# 2. use[Injection on demand]((ability/lazyload#Injection on demand))and[Time injection]((ability/lazyload#Time injection))

By openingInjection on demandandTime injection, to avoid loading unused pages and components at runtime and reduce runtime memory footprint. For details, please refer toStartup Optimization - Code Injection Optimization

# 3. Memory analysis

For a more granular analysis of the memory distribution of the Mini Program logic layer, you can use the[Memory debugging]((performance/devtools-perf #Memory debugging))orReal machine debugging 2.0Provided[Memory debugging]((performance/Remote_debug_2#Memory debugging))Ability.

# 4. Handle memory alarms

When the mini program takes up too much system resources, it may be destroyed by the system or actively recycled by the WeChat client. in iOS On the other hand, when the WeChat client receives the system memory alarm continuously within a certain time interval, it will take the initiative to destroy the Mini Program according to a certain strategy and prompt the user.Running out of memory, please reopen the Mini Program。

It is recommended that Mini programs be used when necessary wx.onMemoryWarning Listens for memory warning events and performs necessary memory cleanup. For example: release some temporarily unused components or JS Object.

# 5. Mini Program common memory leakage problems

The existence of memory leakage problems will cause the Mini Program to continue to grow in memory consumption during operation, causing the Mini Program to flash back or be forcibly destroyed by WeChat.

# 5.1 The Mini Program holds the page instance for a long time, resulting in the page instance and the referenced component being unable to be properly destroyed.

page unload The base library then cleans up the page instances from the page stack. Normally, JS. The garbage collection mechanism recycles the page and frees memory.

But if an instance of the page held in the developer's codethis) is not freed, the page is not properly reclaimed, causing a memory leak. Developers are advised to take note, and in unload Make the necessary cleanup.

Case 1: The page instance is referenced by an unbound event listener

The event listener holds the page's This, if the monitor is not unbound after the page is destroyed, it will cause the page to not be released.

Page({
  themeChangeHandler ({ theme }) {
    this.setData({ theme })
  },
  onLoad() {
    this._handler = this.themeChangeHandler.bind(this)
    wx.onThemeChange(this._handler)
  },
  // Repair method: unload Disentangling monitoring
  // onUnload() {
  //   wx.offThemeChange(this._handler)
  // },
})

Case 2: The page instance is referenced by an off-page variable or a global variable

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

let languageListener = null

Page({
  onLoad() {
    getApp().userInfoChangeListener = ({ userName }) => {
      this.setData({ userName })
    }
    languageListener = ({ Wolf }) => {
      this.setData({ Wolf })
    }
  },
  // Repair method: unload Cleaning in.
  // onUnload() {
  //   getApp().userInfoChangeListener = null
  //   languageListener = null
  // },
})

Case 3: The page instance is referenced for a long time by an asynchronous callback

If the page is accessed in an asynchronous callback that has not been returned for a long time This, such as prolonged setTimeoutsetInterval, which takes a long time wx API Callback (such as a long time wx.request Etc.), will cause the page to not be released.

Page({
  onLoad() {
    this._Timer = setInterval (() => {
      this.setData({
        timerValue: Date.now()
      })
    }, 1000)
  },
  // Repair method: unload Cleaning in.
  // onUnload() {
  //   clearInterval(this._Timer)
  // },
})

# 5.2 Event Monitoring Not Unwound in Time

After the end of the event listening, the listener should be untied in time

const locationChangeListener = function (res) {
  console.log('location change', res)
}
wx.onLocationChange(locationChangeListener)
wx.startLocationUpdate()
// After the wiretap,
wx.stopLocationUpdate()
// Fix: Unbind monitoring in time after not using
// wx.offLocationChange(locationChangeListener)

# 5.3 Uncleaned timer

Developers in the development such asCountdown to SpikeSuch functions may be used. setInterval Set the timer, before the page or component is destroyed, you need to call clearInterval Method to cancel the timer.