pythongarbage-collection

Why disable the garbage collector?


Pythons gc.disable disables automatic garbage collection. As I understand it, that would have quite some side-effects. Why would anyone want to disable automatic garbage collection, and how could one effectively manage memory without it?


Solution

  • One use for disabling the garbage collector is to get more consistent results when timing the performance of code. The timeit module does this.

    def timeit(self, number=default_number):
        if itertools:
            it = itertools.repeat(None, number)
        else:
            it = [None] * number
        gcold = gc.isenabled()
        gc.disable()
        ...
    

    In Python2 and up to Python3.2 gc.disable() is also used to avoid a bug caused by garbage collection occurring between fork and exec. The problem seems to have been fixed in Python3.3 without needing to call gc.disable().