Nevertheless, sooner or later you might face certain issues – for instance, memory leaks. To be able to fix it quickly you should understand exactly how memory allocation operates.
This article describes the basics of memory management, explains how to prevent the most common types of memory leaks and presents the garbage collector solution.
Thus, memory allocation could be defined as the process of “stocking” an area of memory, while freeing it is the return of some space to the system, so that previously occupied space can be reused for other purpose.
When you declare a variable or create a function, the required memory unit goes through the following steps:
Memory application. This is what we have to script in the code: here, reading and writing to memory is came as reading and writing to a variable.
Stack and Heap Allocation Options
Since the size of the data does not change, the engine allocates only a fixed amount of memory for each value.
Such process of assigning memory right before execution is called static.
Because the engine shares a fixed amount of memory for such values, it is possible to assume that there is a limit on the size of primitive values. And depending on the browser used, these limits, as well as the maximum allowed size of the entire stack, may differ.
A memory heap is set to stock objects and functions data .
Unlike the above stack, the engine does not know how much space will be enough for certain objects, and therefore assigns memory as needed.
This particular allocation pattern is called dynamic.
This can be achieved by reading or scripting the value of a variable or an object body, or possibly even by forwarding an argument to a function.
Releasing Memory Space
Most issues with memory management take place at the stage of releasing memory units. The difficult part here is concluding when the assigned memory is no longer needed by the program. Generally, this takes a developer who can seek where in the program a certain piece of memory is no longer necessary and get rid of it.
High-level languages by default have a subsystem called the garbage collector. The main aim of this subsystem is to track all the memory operations and find out when a piece of allocated memory is no longer required. Once it finds it, the garbage collector automatically releases this component.
However, this procedure is not all perfect, since the typical issue of searching whether a certain memory item is needed or not cannot simply be solved through an algorithm.
Majority of garbage collectors operate by collecting memory that cannot be accessed, that is, one that all variables pointing to are out of reach. At the same time, there is always a possibility of freeing memory, since at any time a certain memory area may have variables pointing to it in a certain scope, even though that memory area have never been used in the program.