- Home /
Zero Garbage Policy
Hey,
I'm starting a new project in which I want to really focus on performance. One of my policies for this project is "Zero Garbage".
So I setup a project and implemented a few things that seem to run flawlessly. I bring in the profiler and I get a lot of garbage from Unity under the hood.
I was planning on using the Lightweight scriptable pipeline, but it was generating 2Kb of garbage each frame with a very simple scene with about 5 objects (2000 faces at most).
Few more whacky workarounds for some other garbage generated under the hood (like adding the obsolete GUILayer on Camera, which for some reason will stop generating 0.8Kb of garbage each from from Mouse SendEvents or something like that).
At the moment I'm trying to figure out how to get rid of these 17 bits:
Is this something attainable? Or should I just give up on getting rid of all the garbage generated "by default"?
Thank you!
Note that some of the garbage is editor related. There is an "editor feature" that GetComponent will always return an actual object, even when no component was found. Unity does not return null but a fake null object in order to display a more clear error message when that null reference is used. However that means everytime you use GetComponent with a non existing component, you will allocate a new fake null object.
Though as i said this only happens in the editor. Yes, it's annoying and can't be worked around at the moment. However you can get rid of this by creating a development build and use the profiler on that build just as the documentation suggests. Search for "build" on that site to quickly find the relevant section(s).
edit
Oh, I haven't used it myself yet, but you may be interested in the "garbage free string system" gstring from @vexe . Note that this doesn't help you with any Unity properties or methods that return a string (like obj.name, obj.tag) but it helps with your own string generation.
Another quite useful page is this Unity tutorial about garbage optimisations
Answer by kaarloew · Feb 12, 2019 at 08:11 AM
I would think that currently it is not possible to get to zero garbage in any reasonable way, since there are many .NET and Unity methods that allocate and release memory dynamically. But the situation is getting better since e.g. Span<byte>
is making things more efficient.
https://msdn.microsoft.com/en-us/magazine/mt814808.aspx
Thanks. Seems like a good read. Will make time for it tonight.