However, sooner or later you will encounter some problems – for example, memory leaks – and you will only be able to get rid of them when you understand exactly how memory allocation works.
In this article, I will tell you about memory management and how the garbage collector works, as well as explain how to avoid the most common types of memory leaks.
Memory allocation is the process of “reserving” an area of memory, while freeing it is the return of memory to the system, as a result of which the previously occupied space can be reused.
Each time we declare a variable or create a function, the necessary memory goes through the following steps:
Memory usage. This is what we explicitly write in the code: reading and writing to memory is nothing more than reading and writing to a variable.
Stack and Heap
Stack: Static Memory Allocation
The engine knows that the size of the data will not change, and therefore allocates a fixed amount of memory for each value.
The process of allocating memory right before execution is called static.
Since the engine allocates a fixed amount of memory for such values, it is logical to assume that there is a limit on the size of primitive values. Depending on the browser used, these limits, as well as the maximum allowed size of the entire stack, may vary.
Heap: Dynamic Memory Allocation
A heap (memory heap) is used to store data such as objects and functions.
Unlike with the stack, the engine does not know how much memory will be needed for certain objects, and therefore allocates memory as needed.
This allocation of memory is called dynamic.
This can be done by reading or writing the value of a variable or an object property, or even by passing an argument to a function.
Freeing Up Memory That is No Longer Needed
Most problems with memory management occur at this stage.
The most difficult task is figuring out when the allocated memory is no longer needed by the program. This often requires the developer to determine where in the program a certain piece of memory is no longer needed and release it.
High-level languages have a built-in subsystem called the garbage collector. The role of this subsystem is to track memory allocation operations and use it to find out when a piece of allocated memory is no longer needed. If this is the case, the garbage collector can automatically release this fragment.
Unfortunately, this process is not absolutely accurate, since the general problem of finding out whether a certain memory fragment is needed or not is unsolvable (it cannot be solved algorithmically).
Most garbage collectors work by collecting memory that cannot be accessed, that is, one that all variables pointing to are unavailable. This, however, is too bold an assumption about the possibility of freeing memory, since at any time a certain memory area may have variables pointing to it in a certain scope, although this memory area will never be worked on in the program.