There are three common memory problems with JavaScript:

  • A memory leak
  • Memory ballooning
  • Frequent garbage collection

1. Memory leaks

why

(1) What is a memory leak?

A memory leak occurs when memory that is not needed by a process is not collected by the garbage collection mechanism.

(2) When can JavaScript cause memory leaks?

Memory leaks occur when unneeded memory data is still referenced by other objects because the referenced data cannot be cleaned up.

Common Scenarios

(1) Closure

Closure will refer to the parent function defined in the scope of a variable, the variable will always exist in the memory, until there is no this variable in the process of the referenced data is cleared, the closure of memory data will be clear, reference variables in the closure, should try to minimize the reference data and has reached to reduce memory footprint.

(2) Reference DOM

JavaScript refers to a DOM node object, but when the DOM node is removed, the JavaScript reference is not manually removed, and the reference remains in memory and cannot be reclaimed.

(3) Global variables

The Window object is resident in memory. If you bind an object to a Window object, it is kept in memory until it is no longer needed.

The solution

When writing code that may have memory leaks, it is necessary to pay attention to the scope of the object, handle the reference of the object carefully, and dereference the object when it is no longer needed.

2. Memory expansion

why

(1) What is memory inflation?

Memory inflation means that a large amount of data occupies the memory for a long time.

(2) Why memory expansion?

JavaScript uses a large number of data variables and is always in use. These data are usually redundant and not immediately needed, or when too much unnecessary data is loaded to use space for speed, there is a high probability of memory expansion.

The solution

Manage data reasonably, but load more data that is not needed for the time being, and manage data reasonably by means of caching as needed.

3. Frequent garbage collection

why

(1) What is garbage collection?

Garbage is data that a program keeps in the heap and stack of memory space but is no longer used.

JavaScript is an automatic garbage collection language. The garbage collector of the JavaScript engine automatically collects the garbage generated by JavaScript.

(2) What is the timing of garbage collection?

Garbage collection tasks are interspersed in the main thread and triggered when the garbage storage space is nearly full.

(3) Why is there frequent garbage collection?

Frequent generation of temporary variables, that is, garbage that can be collected quickly, results in frequent garbage collection trips. The main thread task is paused during garbage collection, which can cause pages to stall.

The solution

Try to avoid creating too many temporary variables, and try to optimize the number of variables, such as using reusable variables.