---
title: Memory Optimization
docType: default
---

# Memory Optimization

Miniapps run within limited system resources. When memory usage is too high, the miniapp may be destroyed by the system or proactively reclaimed by the client, forcing users to reopen it — a very poor experience.

## Symptoms of Memory Issues

| Symptom | Possible Cause |
| ------- | -------------- |
| Miniapp suddenly crashes | Memory too high, reclaimed by system |
| Page gets slower over time | Memory leak; available memory gradually decreasing |
| Returning to a previous page is slow | Page stack too deep, consuming large amounts of memory |

## Listen for Memory Warnings

Use [onMemoryWarning](/en/miniapp/develop/miniapp/api/device/memory/onMemoryWarning) to listen for memory warning events and perform necessary cleanup when a warning is received:

```javascript
ty.onMemoryWarning(res => {
  console.warn('Memory warning, level:', res.level);
  // Perform necessary cleanup, such as releasing cache or temporary data
});
```

## Avoid Memory Leaks

### Clean Up Timers Promptly

Timers must be cleaned up when the page unloads:

```javascript
Page({
  onLoad() {
    this._timer = setInterval(() => {
      fetchLatestData();
    }, 5000);
  },
  onUnload() {
    if (this._timer) {
      clearInterval(this._timer);
      this._timer = null;
    }
  }
});
```

### Unbind Event Listeners Promptly

Registered event listeners should be unbound when the page unloads:

```javascript
Page({
  onLoad() {
    this._networkHandler = res => console.log('Network status:', res.isConnected);
    ty.onNetworkStatusChange(this._networkHandler);
  },
  onUnload() {
    ty.offNetworkStatusChange(this._networkHandler);
  }
});
```

## Control Page Stack Depth

A deep page stack consumes large amounts of memory. Choose navigation methods wisely:

| Method | Effect | Use Case |
| ------ | ------ | -------- |
| `ty.navigateTo` | Adds a new page to the stack | Navigating to pages you need to return from |
| `ty.redirectTo` | Replaces the current page | Navigating without needing to return |
| `ty.reLaunch` | Clears the page stack | Post-login redirect to home page, etc. |

## Control Data Scale

Avoid storing excessively large data in `data` or global variables. Use pagination to keep only the data needed for the current view:

```javascript
Page({
  data: {
    list: [],
    page: 1,
  },
  loadMore() {
    const { page } = this.data;
    fetchProducts({ page, pageSize: 20 }).then(res => {
      this.setData({
        list: [...this.data.list, ...res.data], // append, not replace
        page: page + 1,
      });
    });
  }
});
```

## Control Package Size

Package size not only affects download time, but also directly impacts runtime memory. The package must be parsed and executed when loaded; the larger the package, the more memory it consumes. Reducing package size is an effective way to lower the memory baseline.

See [Package Size Optimization](/en/miniapp/develop/miniapp/guide/optimization/startup/package-size).

## Checklist

| Check Item | Optimization |
| ---------- | ------------ |
| Are timers cleaned up on page unload | Call clearInterval/clearTimeout in onUnload |
| Are event listeners unbound on page unload | Unbind event listeners promptly |
| Is page navigation approach appropriate | Use redirectTo for scenarios that don't need to return |
| Is excessively large data being stored | Use pagination; keep only current page data |
