1. Memory storage mechanism

JavaScript is a dynamic language (a language that checks data types during execution), a weakly typed language (a language that implicitly converts data types)

Memory space: code space (storing the execution code), stack space (that is, the execution context stack, storing the execution context. Values of primitive types (string, number, BigINT, Symbol, Boolean, undefined, null) are also stored here. Object types store only a reference address in a pair.

Note: check out lesson 12 on Browser Principles and Practices sometime

Two, how to recycle garbage

1. Stack space: use ESP pointer to switch garbage collection

Heap space: The generation hypothesis: The first is that most objects live very short lives. Second, there are some objects that live a long time.

So the heap is divided into two new generation areas: short lifetime (using the secondary garbage collector) and old generation areas: long lifetime (using the main garbage collector)

2.1. How does the secondary garbage collector in the new generation area of heap space recycle garbage? Firstly, the new generation area is divided into object area and idle area. New objects are stored in the object area, and when it is nearly full, garbage collection is performed.

Start marking garbage, then copy the surviving objects into the free area and arrange them in order, then reverse the two areas. Roles change, so garbage collection is implemented.

2.2. How does the main garbage collector in the old generation area of heap space collect garbage? It uses a mark-sweep algorithm for garbage collection. Mark live objects and junk data, and then remove the junk data.

This is when fragmentation begins, preventing large objects from being allocated contiguous memory. So we use mark-declaim, which is different from the previous algorithm. Instead of cleaning up the garbage, we move the live object to one end and finally clean up the memory beyond the boundary.

If our garbage collection takes too much time on the main thread, we use an alternate execution of markup and JS logic: incremental markup algorithm in order not to cause lag. This breaks down the task of garbage collection into smaller tasks and prevents users from feeling stuck on the page because of garbage collection.

Note: check out lesson 13 on Browser Principles and Practices sometime

Wave in the boat in the garbage recycling attention points (more look is right) : juejin.cn/post/684490…