Cause of memory leak

The heap memory allocated dynamically in the program has not been freed or cannot be freed for some reason. According to the garbage collection mechanism of JS, memory will be reclaimed only when the number of references in memory is 0, 2. Objects touched from the root are marked as no longer in use before being released.

Several cases of memory leaks

  • Global variables: global variable references, variables are not declared
  • Closure: A variable in an inner function has a reference to a variable in an outer function. The closure is not released, which may result in a memory leak
  • Event listening not removed: Repeated listening
  • Cache: The cache is not cleared, so set a maximum cache value

How to avoid it?

  • Eslint detects unexpected global variables
  • Write as few complex closures as possible
  • Remember to clear the binding time when you Destroy

How to solve it?

Heapdump snapshot, memory view memory snapshot

Before and during a leak, objects change by Delta comparison

Closure causes the case


        function Foo(){
            var stage = []
            setInterval(() => {
                debugger
                this.data = {
                    name: 'wbczxxxxxxxxxxxxxxxxxx',
                    hobby: {
                        phone: '11'
                    },
                }
                stage.push(this.data)
            });
        }
        const foo = new Foo()Copy the code


If you are not sure that the closure is causing the problem, you can see that the closure is formed in the lower right corner of the debug tool




After the snapshot, it is found that the memory of Js Arrays objects increases significantly








Through Delta, we found that the number of objects under the array was increasing. Through the key value of the object, we could locate the specific code, and then locate the reference to the external layer variable caused by the closure, and the memory was not released





In addition, you can also view the change of the memory heap over time through Performance in the browser







Finally, we interrupt with a small advertisement