Garbage collection is the name programmers give to the process by which programs free up memory space that is no longer used by objects. So by collecting memory which has been previously allocated to objects, but which is not currently in use in any part of our program we are effectively 'recycling memory'. Conditions for a garbage collectionGarbage collection occurs when one of the following conditions is true:
Garbage collection is implemented differently for every language.Most high-level programming languages have some sort of garbage collection built in. Memory allocation and deallocation methods in Python are automatic. (Click on the graphic to find out what commands relate to garbage collection within Python). Python uses two automatic strategies for memory reallocation:
There are two ways for performing manual garbage collection:
In C programming, developers need to take care of memory allocation and deallocation using malloc() and dealloc() functions - which are to do with memory allocation and the deallocation of that memory. The user has to preallocate or deallocate memory using dynamic memory allocation in languages such as C or C++. However, in the case of C# developers don't need to take care of GC - and it's not recommended to try to do so either. Low-level programming languages may add garbage collection through libraries.
Advantages and Disadvantages of GCGarbage collection is a tool that saves time for programmers. For example it replaces the need for functions such as malloc() and free() which are found in C. It can also help in preventing memory leaks. The downside of garbage collection is that it has a negative impact on performance. This is because GC has to regularly run though the program, checking object references and cleaning out memory. This takes up resources and often requires the program to pause. When should the program do it?If an object has no references (is no longer reachable) then it is eligible for garbage collection. For example in the Java code below, the 'Thing object' originally referenced by 'thing1' has its one and only reference redirected to another object on the heap. This means it is then unreachable and will have its memory unallocated by the garbage collector. ARC (Automatic Reference Counting)ARC is an example of garbage collection. Itis used in Swift, for example. ARC keeps track of the references to all objects that are created. If the number of references drops to 0, the object will be marked for deallocation. Reference for this information: https://www.freecodecamp.org/news/a-guide-to-garbage-collection-in-programming/ and https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals |
|