In
Reference-count approach, we can free the memory whenever object is
eligible for garbage collection (Reference count is reached to 0). But in mark-sweep approach, memory is not
freed whenever the object is eligible for garbage collection.
This
approach runs in two phases.
- Mark Phase
- Sweep phase
Mark
Phase
Whenever
gc (Garbage Collector) is called for garbage collection, It enumerates all the roots and
then starts visiting the objects referenced by them recursively.
Whenever it visits the object, it sets a flag to make sure that
this object is reachable. In the Mark phase we are identifying all
the reachable objects or nodes.
Sweep
Phase
Sweep
starts by iterating through the entire memory and frees memory used
by unreachable objects. Unreachable objects are identified by using
the flag setting , which we are done in Mark Phase.
Advantages
1.
Easy to Implement
2. It
easily reclaims the cyclic structures, (Cyclic structures is a
problem in Reference
Counting Approach).
Disadvantages
1. Entire
heap should be visited in Sweep phase, which impacts performance of
your application.
2. Even
if you identify the reachable object in Mark phase, you are
revisiting them in sweep phase again, Since in sweep phase we are
traversing the entire heap memory.
3.
Mark-sweep collectors tend to leave the heap fragmented.
No comments:
Post a Comment