【Understanding the managed heap】html
一、common problem faced by many Unity developers is the unexpected expansion of the managed heap。dom
二、The 「managed heap」 is a section of memory that is automatically managed by the memory manager of a Project’s scripting runtime (Mono or IL2CPP). ide
managed heap 由 Mono、IL2CPP 的 memory manager 自動管理。ui
三、Crucially, Unity’s garbage collection – which uses the Boehm GC algorithm – is non-generational and non-compacting. 「Non-generational」 means that the GC must sweep through the entire heap when performing a collection pass, and its performance therefore degrades as the heap expands. 「Non-compacting」 means that objects in memory are not relocated in order to close gaps between objects.spa
Unity's garbage collection 不會使用 relocate 來緩解 fragmentation 問題。3d
四、if a large object is allocated and there is insufficient contiguous free space to accommodate the object, as illustrated above, the Unity memory manager performs two operations.code
First, if it has not already done so, the garbage collector runs. This attempts to free up enough space to fulfill the allocation request.orm
Second, If, after the GC runs, there is still not enough contiguous space to fit the requested amount of memory, the heap must expand. The specific amount that the heap expands is platform-dependent; however, most Unity platforms double the size of the managed heap.htm
五、 converting an anonymous method to a closure significantly increases the amount of memory required to pass the closure to method receiving it.blog
closure 比 anonymous method 消費更多內存。
List<float> listOfNumbers = createListOfRandomNumbers(); // anonymous method listOfNumbers.Sort( (x, y) => (int)x.CompareTo((int)(y/2)) ); List<float> listOfNumbers = createListOfRandomNumbers(); int desiredDivisor = getDesiredDivisor(); // closure listOfNumbers.Sort( (x, y) => (int)x.CompareTo((int)(y/desiredDivisor)) );
六、Dictionaries and enums
Enum 做爲 Dictionary 的 Key時,會致使 boxing。 經過提供 Comparer 便可解決此 Boxing。
public class MyEnumComparer : IEqualityComparer<MyEnum> { public bool Equals(MyEnum x, MyEnum y) { return x == y; } public int GetHashCode(MyEnum x) { return (int)x; } }
七、
八、
參考:
一、https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html