Re: Musing about Closures
Posted: Sep 30, 2005 1:24 PM
> Does the usage of closures lead to programmers
> inadvertently extending the lifetime of objects and if so
> is it a significant problem?
The answer to both is "sometimes". Like everything else, you need to be aware of the consequences of your actions. However, it is kind of rare that the problem manifests itself in any meaningful way and when it does, you do the same kinds of things you might when your program hits a size or performance limit. You analyze your usage and optimize somehow.
> Some readers will surely say I worry too much, and in a
> garbage collected language, everything works out magically
> in the end. I am not convinced of that, and I think it is
> important to try and find an implementation technique
> which is efficient, and doesn't quitely make objects last
> longer than intended.
That would typically be garbage collection.
> I am trying to find a happy medium
> between efficiency, and also not be obliged to use garbage
> collection as a crutch for implementing closures.
Except that garbage collection is usually more efficient than manual memory management.
> As an alternative I am considering the possibility of
> auto-destruction semantics for closures. The idea is that
> if a nested function or code-block object refers to a
> variable, its lifetime becomes tied to the lifetime of the
> shortest lived object to which it refers. This approach
> means that closures can be passed to functions, but not
> returned from a function. However functions can still be
> passed from functions. So in a sense what I would be doing
> is somewhat limiting the usefulness of closures, but at
> the same time limiting the associated expenses.
Well, you get what you pay for. I'm not sure about your strategy for cleaning up closures, seems like you'll have a circularity problem. If closure C refers to objects A and B, then A and B must not be destroyed as long as C exists. Saying that C can go as soon as A or B creates a paradox unless you are somehow willing to say "kill A" to trigger this.
It makes for more complexity and smells fragile to me.
> There could be very good reasons for not doing things this
> way, and I would like to hear them. I am also wondering if
> there are alternative implementation approaches which
> don't require a garbage-collector which I can consider.
I don't know of any. As you note, closures vastly increase the complexity of object lifetime management - at some point you should just let the computer handle it.