Python vs Java garbage collection?
Derek Thomson
derek at wedgetail.com
Mon Dec 23 04:44:25 EST 2002
Stuart D. Gathman wrote:
>
> Python uses reference counting. This is the slowest form of garbage
> collection, but it has the virtue that (apart from cycles) memory is
> released at the earliest possible moment.
It has the advantage that it is deterministic, and therefore destructors
can be used to manage non-memory resources, release locks and so on.
Until recently, that is. Suddenly we need to support mark-and-sweep as
well, and so we don't have destructors any more, and need to resort to
"close" methods.
> The problem with Python reference counting, is that it encourages sloppy
> programming like:
>
> data = open('myfile','r').read()
>
> depending on the reference counting GC to release and close the file
> object immediately when read() returns. This habit must be broken before
> Python can evolve to Lisp like speed. The proper code:
>
> fp = open('myfile','r')
> data = fp.read()
> fp.close()
Let he who is without sin, etc.
This code is almost as sloppy. What happens if "read" throws an exception?
>
> is not as pretty. Perhaps some clever pythonista will invent some
> syntactic sugar to help the medicine go down.
>
There is no way. I wish there were. This is a real problem in Java, too.
How do I release locks and non-memory resources without adding functions
like "close" that people have to remember to call all the time?
I understand the benefits of mark and sweep, but there is a real cost
associated with it in terms of potential bugs and creating easy to use
classes.
--
D.
More information about the Python-list
mailing list