Game development Unity Mono memory management: GC mechanism

reference:

        [Unity game development] basic learning of garbage collection

 

to sum up:

The memory usage of the Unity game is divided into the following parts:

  • Mono heap: C# code
  • Native heap: resources, unity engine logic, third-party logic.
  • Library code: Unity library, third-party library.

 

Mono bank:

The memory allocated by the code is allocated on the Mono heap memory through the Mono virtual machine, and its memory footprint is generally small, and the main purpose is to use it when the program logic is processed;

The memory allocated through the interface in the System namespace will be allocated in the Mono heap through the Mono Runtime .

 

Mono memory is divided into two parts,

  • Used memory (used): Used memory refers to the memory that mono actually needs to use
  • Heap memory (heap) : Heap memory refers to the memory that mono applies to the operating system
  • The difference between the two is the free memory of mono .

 

The GC in Mono mainly has the following steps:

  1. Stop all threads that need mono memory allocation.
  2. Traverse all used memory, find those that are no longer needed, and mark them.
  3. Release the marked memory to free memory.
  4. Restart the thread that was stopped.
  5. The memory released by the GC will only be used by mono and will not be returned to the operating system, so the mono heap memory will only increase .

 

Mono memory leak analysis

Typical leak:

Leaks on the code side, due to "there is a wrong reference that should be released but not released", the recovery mechanism thinks that the target object is not "garbage" and cannot be recovered

In the case of manual memory management leaks, resource unloading is actively triggered. After the resource unloading is triggered, the resource references are cleared, but some people forget to unload it actively.

However, the definition needs to be expanded now: the case where the object is no longer needed but not collected by the GC is called mono memory leak

 

the problem we are facing

  • When the managed heap is still insufficient after GC, it will continue to apply for new memory, but the memory released by GC will be reserved for Mono and will not be returned to the operating system, which will cause the game's memory usage to become higher and higher .
  • GC will suspend those threads that need Mono memory allocation, regardless of whether it is called in the main thread or not, it will cause a certain degree of lag.
  • The GC process will perform the time-consuming operation of traversing the mark. Although the memory is optimized, it will undoubtedly greatly increase the burden on the CPU.

Guess you like

Origin blog.csdn.net/qq1090504117/article/details/111775029
Recommended