I have occasionally come across code that manually calls gc.collect()
, but it's unclear why. For what reasons, if any, would it be advantageous to manually run a garbage collection, rather than let Python handle it automatically?
Garbage collection is to release memory when the object is no longer in use. This system destroys the unused object and reuses its memory slot for new objects. You can imagine this as a recycling system in computers. Python has an automated garbage collection.
Manually starting the Garbage Collector (GC) can degrade JVM performance. See list item 4b in Interaction of the Garbage Collector with applications. The GC can honor a manual call; for example, through the System. gc() call.
Garbage collection ensures that a program does not exceed its memory quota or reach a point that it can no longer function. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.
The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection. Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero.
In short, efficiency.
If you are using a pointer to reference something, it is using memory. Even when you stop pointing at it, it still takes up memory for a short amount of time.
Python's garbage collection used to use reference counting. Reference counting is a smart way to tell when something should no longer need memory (by checking how often it is referenced by other objects).
Unfortunately, reference counting is still a calculation so it reduces efficiency to run it all the time (especially when it is not needed), so instead Python now uses scheduled garbage collection.
The issue is that in some specific functionality Python now doesn't garbage collect immediately when it notices something is no longer used (as in the case with reference counting) because it garbage collects periodically instead.
You generally need to run garbage collection manually in a lot of server applications or large scale calculations where minor infractions in garbage collection matter to free memory.
Here is a link from Digi.com that sums it up perfectly if my explanation isn't clear. I hope this helps Brendan!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With