With the development of hardware technology in recent years, and the introduction of GC in high-level programming languages, these changes have allowed us to develop functions without having to pay special attention to memory usage. So why are we revisiting memory management here?

Why does memory need to be managed?

function fn() { arrs = []; Zhangsan arrs [10000] = ' '; } fn()Copy the code

After executing the function, we find that its memory changes are the same as the blue line in the figure above, which keeps rising and does not fall back, indicating a memory leak. As for how to leak, we don’t have to worry about it. I’m just trying to point out that we don’t understand how memory management works when we write code, and we’re more likely to write code that has memory problems that we don’t know about, and that causes the page to stall or even crash.

What is memory management

  • Memory, also known as internal Memory and main Memory, is used to temporarily store computational data in the CPU and data exchanged with external Memory such as hard disk. In short, memory consists of read and write units, representing a piece of operable space;
  • Management: the artificial manipulation of the application, use and release of a space.
  • Memory management: developers actively apply for space, use space, free space

Memory life cycle

Regardless of the programming language, the memory life cycle is basically the same:

  1. Allocate as much memory as you need
  2. Use allocated memory (read, write)
  3. Release \ return it when it is not needed

Apply -> use -> release;

Memory management in js

Low-level languages like C typically have low-level memory management apis, such as malloc() and free(). JavaScript allocates memory automatically when variables (objects, strings, etc.) are created, and automatically frees them when they are not used. This “automation” is a source of confusion and gives JavaScript (and other high-level languages) developers the false sense that they can afford not to care about memory management. The following code demonstrates the application, use and release of memory

// let obj = {} // use (read/write) obj.name = 'zhangsan' // release obj =null;Copy the code

Reference:

  • Memory management