Hi forum,
I’m wondering why python uses both reference counting and garbage collection.
Objective-C and Swift use only Automatic Reference Counting (ARC) to manage memory usage. Can Python use ARC too and eliminate Garbage Collection?
Hi forum,
I’m wondering why python uses both reference counting and garbage collection.
Objective-C and Swift use only Automatic Reference Counting (ARC) to manage memory usage. Can Python use ARC too and eliminate Garbage Collection?
No. CPython already uses reference counting for the vast bulk of its memory recycling. gc
is needed in CPython only to reclaim trash in cycles. ARC doesn’t address that at all. Here’s a line from the document you linked to:
It [ARC] does not provide a cycle collector; users must explicitly manage the lifetime of their objects, breaking cycles manually or with weak or unsafe references.
Why do you want to eliminate Python’s garbage collection?
Technically, reference counting is garbage collection, and
CPython has two garbage collectors: the automatic reference counter, and
a second gc system for eliminating garbage in cycles.
Other Python implementations use different systems:
IronPython uses the .Net garbage collector, whatever that is;
Jython uses the JVM garbage collector, and has no reference counter;
PyPy allows you to choose different garbage collectors at build-time, when you compile the interpreter.
Older versions of CPython used only reference counting, and we needed to manage cycles manually. I would not want to go back to those Bad Old Days.
Thanks Tim,
I think ARC does release memory and weak ref is used to stop cycle reference in Swift. I found that weakref
mentioned in Python too: cpython/Doc/tutorial/stdlib2.rst
.
Thanks Steven,
I’m new to Python and did’t know that.
Do you mean people used weakref to stop cycle reference in their python script code before?
No, this was before weak references existed.
Weak references were added in version 2.1.
https://docs.python.org/2.7/library/weakref.html
The cyclic garbage collector was added in Python 2.0:
so anyone who used Python 1.x had to manage cycles manually.
For what it’s worth, you can do
import gc
gc.disable()
to disable the garbage collector. Then you only have reference counting. That’s mentioned in the gc
module docs:
“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.”
https://docs.python.org/3/library/gc.html
The drawback is that cycles are no longer collected. If you have a cyclic data structure, you need to either use weak references or “de-cyclicize” your structure when you no longer need it. I guess it could also prevent the interpreter from collecting some of its internal structures, which could contain cycles, though I don’t know about that too much.
So, Python without GC is conceptually possible. But it would make Python a vastly different language.