On Thursday 09 September 2010 20:17:23 Andrej Mitrovic wrote: > Related: Do stack variables get freed on exit or do they just get marked as > unused by the GC? Because I'm not seeing any memory increase over time. I > guess I have to read more about how allocation works. :p > > Jonathan M Davis Wrote: > > _every time_ that you use hit or > > > hot in main(), you're calling hit() and hot() and creating them all over > > again
A variable on the stack has nothing to do with the GC unless it's in a delegate (since then the delegate must have its stack in a separate area on the heap). Now, dynamic arrays live on the stack, even if their references don't, so allocating a bunch of those will obviously require more memory. However, in this case, he's done with the array as soon as he's used it, so the GC (which if I understand correctly is called every time that new() is - or at least has the opportunity to run every time that new() is called) can reclaim it right away. There's a decent chance that he only ever allocates one array's worth of memory from the OS. Certainly, he wouldn't end up allocating new memory from the OS every time that he calls hit() or hot(). Every time that new is called, the GC will allocate the memory that it's asked to from its heap. At least some of the time that new is called, the GC will check to see if any of its heap memory can be recovered, and then recover it (so it's deallocated from the programs perspective but not returned to the OS). If the GC needs more memory than it has free on its heap, it will allocate more from the OS. Ideally, the GC would also look at how much memory that it has in its heap vs how much the program is currently using and then return some of it to the OS if it has too much free, but as I understand it, it doesn't currently do that. So, once your program uses a certain amount of memory, it won't ever use any less until it terminates. Presumably, that will be fixed at some point though. - Jonathan M Davis