setting say... array to
null
and letting GC clean up the only way to clean up memory in that case
well, the first bit is probably wrong, unless arr
was actually (say) a field of another object that is going to continue to live for a long period of time. In your example, arr
was a local variable, and the GC and JIT conspire (when you're running release code, not debug) to know the lifetime of such variables very accurately. They know that arr
isn't used again and is so eligible for garbage collection - there's no need to assign null
to it.
Now, to the broader question - no, there's no way to hand memory back eagerly. It would actually be more work to allow you to tell the GC "please take back this block of memory now"1. GC.Collect
, as you say, is frowned upon, because even that isn't really "please take back this block of memory I'm no longer using", it's "please run your full analysis to determine all blocks of memory that are no longer required, then perform compaction, etc".
1The managed memory system has a trivial way of keeping track of available memory for new allocations - it's at the end of the block of all previous allocations. So compaction is the only way that released memory can be reused.