๐จ๐ป๐ถ๐๐ ๐๐ฒ๐๐: ๐ฆ๐๐ผ๐ฝ ๐ฆ๐๐ฎ๐ฟ๐๐ถ๐ป๐ด ๐ฌ๐ผ๐๐ฟ ๐๐ฟ๐ฎ๐บ๐ฒ ๐ฅ๐ฎ๐๐ฒ
Many Unity games suffer from frame rate stutters. These stutters often come from Garbage Collection (GC) spikes. Even with modern tools, developers often ignore memory discipline.
Every string addition and every new list creates memory pressure. These small actions add up. They cause the CPU to pause your game to clean up memory.
You must stop treating memory as an infinite resource. Use these three methods to keep your frame rates smooth.
- Fix String Allocations Strings are immutable. If you use the + operator to join strings, you create new objects in memory every time. This kills performance.
- Bad: string log = "Player " + id + " scored " + score;
- Good: Use a static StringBuilder. Clear it and reuse it to build your text. This creates only one allocation for the final result.
- Manage Temporary Buffers Creating new lists frequently causes major allocations. When a list grows, it allocates more memory.
- Bad: Creating a new List
inside a loop or a frequently called function. - Good: Use ArrayPool
. Rent an array from the pool, use it, and return it when finished. Combine this with Span to work with the memory without making copies.
- Avoid LINQ in Hot Paths LINQ is easy to write but it creates hidden objects. Methods like Where or Select create enumerators that trigger the GC.
- Bad: allObjects.Where(obj => obj.activeSelf).ToList();
- Good: Use a standard foreach loop. Pass in a pre-allocated list to store your results. Use .Clear() on that list instead of creating a new one.
Memory discipline makes your game feel polished. Minimize your allocations to provide a smooth experience for your players.
Source: https://dev.to/prabashanadev/unity-devs-stop-starving-your-frame-rate-25ep