Idea: "Frozen" inner function
Jarrett Billingsley
kb3ctd2 at yahoo.com
Sat Nov 25 08:47:58 PST 2006
"Michael Butscher" <mbutscher at gmx.de> wrote in message
news:MPG.1fd2668cdc5c74998969d at news.digitalmars.com...
> The only efficiency tradeoff of frozen functions is the copying at the
> time of definition (and later the freeing of the context memory).
> Except for that they would be as efficient as inner functions.
If in a loop, or in a function which is called a lot, that would be a lot of
allocations, which is particularly wasteful if you never return the closure
from the function. I'd say a very large percentage of the time, you don't
need to return nested functions, so it'd be wasteful to enable the feature
when it's not used that often.
Additionally, there's the problem of functions with several levels of
nesting. If you have c() inside b() inside a(), if c() accesses local
variables of both b() and a(), when b() returns (but still inside a()), the
closure of c() will have to be able to access the active locals of a() on
the stack, but the locals of b() will have to be on the heap. This would
have to be done through some second level of indirection or using multiple
context pointers. This problem exists in languages such as Lua (and mine,
MiniD!) and is handled with tricky things called upvalues, which are a
second level of indirection for each outer function local. I don't know how
well something like that would fit into a lower-level language like D.
> This would be technically the same, but, as you wrote, less convenient.
For the time being, though, it's certainly a nice (and simple) alternative /
workaround. It also has the advantage that you can very selectively control
if/when the closure's context is allocated on the heap.
More information about the Digitalmars-d
mailing list