Why disable the garbage collector?

后端 未结 4 1541
死守一世寂寞
死守一世寂寞 2021-02-07 00:09

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 colle

4条回答
  •  时光说笑
    2021-02-07 01:01

    From the same page you link to:

    Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles.

    So that answers the second part of the question, "how could one effectively manage memory without it". Don't create reference cycles. It's a fairly limited use case, sure.

    For the first part of the question the answer is performance. Again, a fairly limited use case.

    Disabling GC would only help if (a) the GC is actually doing work, and (b) that work is achieving nothing, that is to say it's finding nothing to free, or finding so little that you think your program can tolerate the leak for as long as GC is disabled. So, if your program is too slow and doesn't create reference cycles and disabling GC appears to speed it up, then you would consider disabling GC.

    I speculate (based on previous GC that I've seen, not Python's in particular) that if you don't allocate any memory then the garbage collector won't have any long-term performance cost. It might have some short-term and unpredictable cost tidying up what has gone before. So even in the case where you're going into a massive numpy number-crunching routine and think you should look to squeeze all possible performance out of that part of the code, disabling GC while you do it still wouldn't help. It will just delay the time cost of tidying up previous reference cycles until after you re-enable GC.

    Arguably, programs that run for a short time and don't use much memory do not need garbage collection, they can tolerate leaks. But even more arguably, if you start out thinking like that you will eventually get into trouble with a program that leaks more memory than you expected.

提交回复
热议问题