javascriptThe column introduces the garbage collection mechanism, memory leaks, and closure contents. Let’s take a look at the fast-end bench.
Write at the front: This is a series I am about to start writing in the javascript column, mainly in the framework of rampant In the era, although I use a framework for work, for interviews and technical advancement, the basic knowledge of JS is the icing on the cake, and it is also a piece of knowledge that I have to learn. Although you don’t need to know a lot about cars to drive a car, you only need to master the common uses of cars. Just function. But if you know cars, you can drive better, and by the same token. Of course, an article will not just talk about one knowledge point. Generally, related knowledge points will be connected in series. While recording your own learning, you will share your own learning and encourage each other! If you can, please also please give me a like, your likes will also make me work harder to update!
Overview
Eating time: 6-12 minutes
Difficulty: Easy, don’t run, watch before leaving
Garbage collection mechanism
The previous blog mainly explains the allocation and use of memory (stack memory and heap memory, deep copy and shallow copy). After use, of course, Returning unused memory is like clearing unused software on your phone from the background, which can improve the running speed of your phone. Otherwise, if more and more memory is used, it will get stuck sooner or later. The same goes for JS.
Every once in a while, the garbage collector of JS will "patrol" the variables, just like security patrols in the park, letting irrelevant people leave quickly . When a variable is no longer needed, it will release the memory space occupied by the variable. This process is called Garbage Collection
JS Garbage There are two types of recycling algorithms, reference counting and mark clearing.
Reference counting method
The reference counting method is the most basic garbage collection algorithm and has been used by modern browsers. The equipment has been eliminated. Before learning the reference counting method, you need to first have a certain concept of reference. You can think of it as a description of the memory address pointed to by the current variable, which is somewhat similar to the memory pointer of the JS reference data type. To understand the concept, let’s first look at a line of code:
var obj={name:'jack'};复制代码
Copy after login
When we assign a value to obj, we actually create a reference pointing to the variable, reference count is 1, Under the mechanism of reference counting, each value in the memory will correspond to a reference count
, and when we assign a value to obj, it is When null, this variable becomes a piece of useless memory. At this time, the reference count of obj will become 0, and it will be garbage collected. The memory space occupied by obj will be released
We know that the life cycle of the function scope is very short. After the function is executed, the memory space inside Variables are basically useless variables. The consequence of not clearing them is that the memory garbage is not released, and it still occupies the original memory and does not let go, which will easily cause memory leak. Let’s first look at a piece of code and Running results:
function changeName(){ var obj1={}; var obj2={};
obj1.target=obj2;
obj2.target=obj1;
obj1.age=15; console.log(obj1.target); console.log(obj2.target);
}
changeName();复制代码
Copy after login
##We can see that obj1.target and obj2.target have mutual references. situation, because when obj1.age is changed, obj1.target.age and obj2.target.age are also affected at the same time, and they point to The reference count is consistent When the function is executed,
obj1 and obj2 are still alive and well, because obj1.target and ## After the execution of #obj2.target is completed, the reference count is still 1. It is clear that the function has been executed, but this kind of garbage still exists. There are too many such functions defined, Memory leakIt will also be unavoidable
Mark clearing method
The disadvantages of the above reference counting method are already obvious, so now we are going to talk about the marking clearing method There is no such problem. Because the judgment standard it uses is to see whether the object
can be reached
, it is mainly divided into two stages, marking stage and clearing stage:
Marking phase
The garbage collector will start from the root object (Window object) and scan all reachable objects. This is the so-called
reachable
Clear phase
While scanning, objects that cannot be reached by the root object (
unreachable
) are objects that are considered unnecessary and will be cleared as garbage
现在再来看下上面的代码
function changeName(){ var obj1={}; var obj2={};
obj1.target=obj2;
obj2.target=obj1;
obj1.age=15; console.log(obj1.target); console.log(obj2.target);
}
changeName();复制代码
The above is the detailed content of Understand the garbage collection mechanism, memory leaks, and closures of JS series (3) with one piece of paper. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.
A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.
Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.
Valgrind detects memory leaks and errors by simulating memory allocation and deallocation. To use it, follow these steps: Install Valgrind: Download and install the version for your operating system from the official website. Compile the program: Compile the program using Valgrind flags (such as gcc-g-omyprogrammyprogram.c-lstdc++). Analyze the program: Use the valgrind--leak-check=fullmyprogram command to analyze the compiled program. Check the output: Valgrind will generate a report after the program execution, showing memory leaks and error messages.
A memory leak in C++ means that the program allocates memory but forgets to release it, causing the memory to not be reused. Debugging techniques include using debuggers (such as Valgrind, GDB), inserting assertions, and using memory leak detector libraries (such as Boost.LeakDetector, MemorySanitizer). It demonstrates the use of Valgrind to detect memory leaks through practical cases, and proposes best practices to avoid memory leaks, including: always releasing allocated memory, using smart pointers, using memory management libraries, and performing regular memory checks.
Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.
Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.
Anonymous functions are concise and anonymous, but have poor readability and are difficult to debug; closures can encapsulate data and manage state, but may cause memory consumption and circular references. Practical case: Anonymous functions can be used for simple numerical processing, and closures can implement state management.