Unity never freeing large array

Is there a way to increase the threshold before which the garbage collector decides it needs to take action?

In a standalone (PC) project, I was using File.ReadAllBytes() to read a video file into memory. Turns out the resulting byte[ ] array was never being freed. Now, I know, garbage collector and all that.

But in some cases this was a very large file. And the end result was actually running out of memory when a file needed to be read in whose size exceeded the amount of available memory, simply causing the video to not play.

Why are you reading all the bytes of a video file??? That’ll be humongous.

Why not use a stream, much more memory efficient.

Sorry if the past tense didn’t make it clear: I’ve already replaced that code.

But I’m similarly loading textures (downloaded from a server) by using ReadAllBytes and then creating a Texture2D from that. I’m worried now that that memory might not be getting freed either.

Make sure you orphan any references to the array. As long as nothing references, the garbage collector will clean it up, when it does a pass.

Thing is, it doesn’t do a pass immediately after you orphan the array. It will when it recognizes the heap is filling up. It only notices when it actually looks… this might happen when you go to allocate memory for another brand new object. Or it might happen because it just hasn’t looked in a while and it figures to take a look. I’m not actually sure all the triggers for the version of mono Unity uses.

Either way, it’ll get cleaned up when the time comes.

Just make sure you don’t maintain a reference to it, that’s all. Set that variable = null.