Last night, I dealt with an annoying memory leak issue on my YouTube Downloader. For those that don’t know what a memory leak is, basically my program used more and more memory, without ever freeing it, so it would eventually use all available memory on my computer. By memory, I’m talking about volatile memory, or RAM (Random Access Memory). Every single time I loaded an image into memory, the RAM usage would increase. I first noticed the problem when the application complained that it was out of memory. I export it as a 32 bit app so that the maximum possible audience is able to make use of it. However, one restriction of 32 bit apps are their limited use of RAM (4 GB). So that meant I was filling up 4 Gigabytes of RAM while trying to load a few images. That didn’t seem right. I exported it as a 64 bit application to check what was going on, and the Downloader filled up 15 GB of my RAM in about 4 seconds. Whoops. I started digging through my code. What was never getting freed? I tried manually calling the garbage collector. Nothing. I spent hours commenting out lines and lines of code, watching Task Manager like a hawk, seeing whether the code I had changed would make any difference. And the memory usage kept climbing. Eventually, it didn’t. Turns out it was a Unity function. After some more reading, it turns out that texture.LoadImage (replaced by ImageConversion.LoadImage) is not automatically garbage collected, for whatever reason. In fact, it’s never unloaded at all unless you call Destroy() on it. Once I set it up to Destroy the textures after they weren’t needed, the memory usage dropped to around 70MB instead after downloading the songs. Much better. In the process of trying to find the bug, I made my original code much more efficient, because I thought it was the issue at first. I’m not really sure what there is to learn from this, but it sure was frustrating.
My Patreon | My Website