LINQ and ZLinq in the Unity 6 Era: Avoiding GC Allocations in Large-Scale Projects
Introduction In large-scale Unity development, GC Alloc can quietly become a real problem. At first, nothing looks wrong. But as the project grows and you add more enemies, UI, master data, events, states, notifications, logs, and other systems, small allocations that happen every frame begin to pile up. LINQ is especially convenient. var aliveEnemies = enemies . Where ( x => x . IsAlive ) . OrderBy ( x => x . DistanceToPlayer ) . ToList (); It is readable. But if this kind of code runs every frame, it can become a source of both GC Alloc and CPU overhead. Unity's official documentation also recommends reducing frequent managed heap allocations as much as possible, ideally getting close to 0 bytes per frame. https://docs.unity3d.com/2022.3/Documentation/Manual/performance-garbage-collection-best-practices.html For general GC Alloc best practices, this article refers to the Unity 2022.3 documentation, because the general guidance still applies. Unity 6-specific GC behavior is covered later using the Unity 6.0 documentation. This article assumes Unity 6.0 as the minimum Unity version and explains how to choose between regular LINQ and ZLinq in production code. Unity 6.0 uses the Roslyn C# compiler, and its C# language version is C# 9.0. However, some C# 9 features, such as init-only setters, are not supported. https://docs.unity3d.com/6000.0/Documentation/Manual/csharp-compiler.html The short version The point of this article is not to ban LINQ completely. Do not use LINQ in hot paths just because it is readable. Do not assume ZLinq solves everything just because you introduced it. Those are the two main ideas. A rough guideline looks like this: Area Guideline Editor extensions, build scripts, debug code Regular LINQ is usually fine Startup, loading, initialization LINQ can be fine, but measure when data size is large Update / LateUpdate / FixedUpdate Avoid LINQ by default Code that is not per-frame but still called frequently Consider ZLinq Code that materializes res