Reputation: 10720
Following up my previous question regarding Profiler spikes. I have just figured out that if I enable deep profile option in Unity3D I can see GetComponent()
call under ScrollRect.LateUpdate()
is taking up to 2.4 MB memory for garbage collection for only 5 Scroll Rect
components. As it is obvious from the following snapshot that Unity is calling Component.GetComponent()
for 4046 times in LateUpdate()
method which causes performance issue. My application is UI intense, but 2.4MB for GC is not accepable at all.
Usually It is recommended not to use GetComponent()
in any of update methods but Unity's own implementation is breaking the convention. Which limits the number of UI items I can have in one scene to avoid the performance issues.
Note this profiling data is only from the frame when I activate a menu object.
Is there any workaround to reduce/save 2.4MB of memory?
Upvotes: 3
Views: 2819
Reputation: 125275
Usually It is recommended not to use GetComponent() in any of update methods but Unity's own implementation is breaking the convention
Unity's GetComponent()
does not allocate memory when the Application it is built. Build the Application to verify this. It allocates memory only in the Editor.
Unity made a post about this few years ago:
We do this in the editor only. This is why when you call GetComponent() to query for a component that doesn’t exist, that you see a C# memory allocation happening, because we are generating this custom warning string inside the newly allocated fake null object. This memory allocation does not happen in built games. This is a very good example why if you are profiling your game, you should always profile the actual standalone player or mobile player, and not profile the editor, since we do a lot of extra security / safety / usage checks in the editor to make your life easier, at the expense of some performance. When profiling for performance and memory allocations, never profile the editor, always profile the built game.
It is recommended to profile the real game instead of the one from the Editor.
Upvotes: 5