Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Does javascript have a garbage collection mechanism, gc?

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, what the editor shares with you is whether javascript has a garbage collection mechanism gc. I believe many people do not know much about it. In order to make you understand better, I have summarized the following contents for you. Let's look down together. I'm sure you'll get something.

There is a GC (garbage collection mechanism) in javascript. JavaScript is a language that uses the garbage collection mechanism, and the execution environment is responsible for managing memory when the code is executed, automatically destroying garbage objects (objects that are not referenced) from memory.

Garbage Collection Mechanism (GC) in JavaScript

Concepts related to garbage collection

①, what is rubbish?

Objects that are not used (referenced) are rubbish.

②, what is garbage collection?

Objects that are not referenced are destroyed and memory is freed, which is garbage collection.

Programming languages such as C and C++ require manual garbage collection.

Java, JavaScript, PHP, Python and other languages automatically garbage collection.

JS has an automatic garbage collection mechanism, which will automatically destroy these garbage objects from memory. We do not need and cannot carry out garbage collection operations. All we need to do is set the object that is no longer in use to null.

Why do you need garbage collection

In C / C++, tracking memory usage and managing memory is a great burden for developers.

JavaScript is a language that uses garbage collection, that is, the execution environment is responsible for managing memory during code execution, helping developers get rid of this burden.

Memory allocation and resource recovery through automatic memory management

The basic idea is simple: determine which variable will no longer be used and free up its memory space.

This process is periodic, meaning that the garbage collection program runs at regular intervals.

For example, the memory of objects, strings and objects in JS is not fixed, and memory will be allocated dynamically only when it is really used.

This memory needs to be released after it is not used so that it can be used again, otherwise it will crash after the available memory of the computer is exhausted.

The main methods of garbage collection in the history of browser development are

Citation counting method

Label elimination method

Citation counting method

Train of thought

Variables are just references to values

When the variable refers to the value, the number of references is + 1

When the reference to the variable is overwritten or cleared, the number of references is-1

When the number of references is 0, the memory can be safely freed.

Let arr = [1,0,1] / / [1,0,1] the memory referenced by arr is referenced by 1arr = [0,1,0] / / [1,0,1]. The memory referenced by 1const tmp = arr / / [0,1,0] is referenced by tmp 2 times.

Circular reference problem

Netscape Navigator 3.0 adoption

In this example, the properties of ObjectA and ObjectB refer to each other respectively

After the execution of this function, the number of references to the Object will not become 0, affecting the normal GC.

If executed multiple times, it will cause a serious memory leak.

The mark removal rule does not have this problem.

Function Example () {let ObjectA = new Object (); let ObjectB = new Object (); ObjectA.p = ObjectB; ObjectB.p = ObjectA;} Example ()

Solution: point it to null at the end of the function

ObjectA = null;ObjectB = null; Mark removal

In order to solve the problem of memory leakage caused by circular references, Netscape Navigator 4.0began to adopt tag cleanup.

By 2008, IE, Firefox, Opera, Chrome, and Safari all used tag cleanup (or its variants) in their JavaScript implementations, but differed in how often they ran garbage collection.

Train of thought

Mark "enter" when the variable enters the execution context

At the same time, mark "leave" when the variable leaves the execution context.

Henceforth, this variable cannot be accessed

Free memory during the next garbage collection

Function Example (n) {const a = 1, b = 2, c = 3; return n * a * b * c;} / mark Example to enter the execution context const n = 1; / mark n to enter the execution context Example (n); / / mark a line to enter the execution context console.log (n); / / mark a line to leave the execution context and wait for garbage collection

Const and let claims to improve performance

Const and let not only help improve the code style, but also improve the performance of garbage collection.

Const and let give JS a block-level scope, and when the block-level scope ends earlier than the function scope, the garbage collector intervenes earlier

Reclaim the recycled memory as soon as possible to improve the performance of garbage collection

Garbage collection of V8 engine

The garbage collection of V8 engine adopts mark removal method and generation recovery method.

Divided into the new generation and the old generation

The new generation

The new generation of garbage collection adopts Scavenge algorithm

Allocated to commonly used memory and a small amount of newly allocated memory

Memory size

32-bit system 16m memory

64-bit system 32m memory

Zoning

The new generation of memory is divided into the following two areas, each accounting for half of the memory

From space

To space

Running

Only From space is actually running.

To space is idle

Scavenge algorithm

Solved the problem of memory fragmentation (discontiguous memory space)

It's the equivalent of trading space for time.

Start garbage collection when From space memory usage is about to reach the upper limit, and mark all unreachable objects in From space

Copy untagged objects from From space to To space.

Then empty the From space and leave it idle, which is transformed into a To space, commonly known as reversal.

The new generation-> the old generation

Memory up to 25% of From space

Experienced a reincarnation of From space To space

The new generation stores a small amount of newly allocated memory. If one of the following conditions is met, it will be allocated to the older generation.

The old generation

Mark-sweep marker removal and mark-compact marker finishing are used in the old generation.

Usually store larger blocks of memory and blocks of memory allocated from the Cenozoic generation

Memory size

32-bit system about 700m

64-bit system about 1.4G

Zoning

Store compiled code

Store the mapping relationship of storage objects

The larger amount of memory that cannot be stored in other areas is basically more than 1m.

Literally, the old generation stores the memory allocated by the new generation.

Old Object Space

Large Object Space

Map Space

Code Space

Recycling process

After the marking is complete, the objects marked as Class 1 are freed of memory.

Use depth-first traversal, traversing each object.

First, all non-root objects are marked as Class 1, and then depth-first traversal is performed.

Objects are pushed onto the stack during traversal, during which objects are marked as category 2.

Traversal completes the unstack of the object, which is marked as type 3.

The whole process until the stack is empty.

Unscanned and recyclable, hereinafter referred to as Category 1

In scanning, it cannot be recycled, hereinafter referred to as category 2

Scan completed and cannot be recycled, hereinafter referred to as category 3

Tag classification (tricolor marker)

Ergodic

Mark-sweep

Mark-compact

After garbage collection, the memory space is discontiguous.

This can easily cause the problem of not allocating a large amount of memory space, thus triggering garbage collection.

Therefore, there are Mark-compact steps to organize unrecycled blocks of memory into contiguous memory space.

Frequently triggering garbage collection will affect the performance of the engine, and Mark-compact will be triggered first when the memory space is insufficient.

Garbage collection optimization

Increment mark

If you use a centralized period of time for garbage collection, the new generation is fine, and the older generation may cause stutters if they traverse larger objects.

Incremental tagging: make garbage collectors and application logic programs run alternately, thinking like Time Slicing

Parallel recovery

In the process of garbage collection, several auxiliary threads are opened to improve the efficiency of garbage collection.

Concurrent recovery

During the execution of a logic program, several worker threads are opened for garbage collection and memory that has no logical relationship with the main thread.

Memory leak scenario

Global variable

/ / exm1function Example () {exm = 'LeBron'} / / exm2function Example () {this.exm =' LeBron'} Example ()

Uncleared timer

Const timer = setInterval (() = > {/ /...}, 1000) / / clearInterval (timer)

Closure

Function debounce (fn, time) {let timeout = null; return function () {if (timeout) {clearTimeout (timeout);} timeout = setTimeout (()) = > {fn.apply (this, arguments);}, time);} const fn = debounce (handler, 1000); / / fn references timeout

Uncleared DOM element references

Const element = {/ / here reference DOM elements button:document.getElementById ('LeBron'), select:document.getElementById (' select')} document.body.removeChild (document.getElementById ('LeBron')) how to detect memory leaks

In fact, this is not difficult. The original developer tool Performance in the browser will do.

Steps

F12 Open developer tools

Select the Performance toolbar

Check the screenshot and Memory

Click to start recording

Finish recording after a period of time

Result

Heap memory is allocated and released periodically

If the min value of heap memory is gradually increasing, there is a memory leak.

Optimize memory usage

1. Try not to define functions in for loops.

/ / exmconst fn = (idx) = > {return idx * 2;} function Example () {for (let iTunes * 2; / /} const res = fn (I);}}

2. Try not to define objects in the for loop

Function Example () {const obj = {}; let res = ""; for (let I = 0; I < 1000; iTunes +) {/ / const obj = {/ a: I, / b: I * 2, / / c: I * 3, / /}; obj.a = I; obj.b = I * 2; obj.c = I * 3; res + = JSON.stringify (obj);} return res}

3. Empty the array

Arr = [0,1,2] arr.length = 0; / / cleared the array, array type unchanged / / arr = [] / / re-applied a piece of empty array object memory about javascript garbage collection mechanism gc? so much for sharing here. I hope the above content can have some reference value for you, and you can learn to apply it. If you like this article, you might as well share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report