Tuesday, November 20, 2012

Why does Garbage Collection only sweep the heap?


Why does Garbage Collection only sweep the heap?

Q:
Basically, I've learned so far that garbage collection erases forever any data structure that is not currently being pointed to. But this only checks the heap for such conditions.
Why doesn't it also check the data section (globals, constants, etc etc) or the stack as well? What is it about the heap that it's the only thing that we want to be garbage collected?
A: 
The garbage collector does scan the stack -- to see what things in the heap are currently being used (pointed to) by things on the stack.
It makes no sense for the garbage collector to consider collecting stack memory because the stack is not managed that way: Everything on the stack is considered to be "in use." And memory used by the stack is automatically reclaimed when you return from method calls. Memory management of stack space is so simple, cheap and easy that you wouldn't want garbage collection to be involved.

No comments:

Post a Comment