I had been meaning to come up with some sort of number display so I can write numbers (like the amount of Garbage) to the screen without worrying about it creating garbage. Well, I finally got around to it, and low and behold, my GC came to a complete halt. At first, I wasn’t so sure–perhaps my new number display was a bit off–so I threw in a couple lines that would specifically create garbage. Sure enough the GC kicked right back up again.
As you can imagine, I’m very happy. Now I can know what, exactly, is causing garbage the second I add it in. And already I’ve realized that I was wrong in thinking every class object that is added to a list creates garbage; it doesn’t! When I added those lines to test my display, I apparently had made an error. I added some class objects to a list that were from my already created pool of objects. The problem was that I still wasn’t seeing any garbage. I got a little worried because I figured that that meant there was a bug in my number display, but after a few minutes, I discovered the error.
Rather than adding objects from my pool, I added some newly creates ones–empty objects created in-line with the list. I ran the program and there it was; the GC was creating garbage again.
All this time, I always thought that that adding any class reference to a List would create garbage, but that’s not the case. As long as you add a reference form an object that will never be destroyed–say, one from an object pool–then no garbage will be created.