How Nested Functions Work, part 1

Jeremie Pelletier jeremiep at gmail.com
Sun Aug 30 18:00:12 PDT 2009


Walter Bright Wrote:

> http://www.reddit.com/r/programming/comments/9fk6g/how_nested_functions_work_part_1/

I really like the way nested functions and closures are done in D. Especially because they are the same thing as delegate and closures.

But speaking of closures, I did notice something that could be optimized:

void foo {
    int a;
    void foo2() { a++;}
    bar(&foo2);
}
void bar(in void delegate() dg) { dg(); }

Here foo() is using _d_allocmemory to get storage for the stack frame. I understand it is for cases where the closure is executed long after the owner method has returned, but if the delegate has a scope storage class it could use the thread's stack instead.

Using nested functions alone does use the stack for storage, unless you need to use a local delegate to fix forward references within nested functions resulting in _d_allocmemory allocating the stack frame, as in the following example:

void myFoo() {
    int a;
    scope void delegate() bar = void;
    void foo() { bar(); }
    void foo2() { a++; if(a != 10) foo(); }
    bar = &foo2;
    foo();
}

Closures in D is an amazing feature and I really miss it when I need to use another language (I can't find an employer who wants D code, but I keep my fingers crossed!), but here is yet another feature I try to avoid in time critical code right now because of the expensive call into the memory manager when I can write longer code that executes on stack storage.

Anywho, thanks for the link Walter, I'm not really familiar with C# and it's nice to know D beats its syntax, I would hate to have to assign delegates for every nested function!



More information about the Digitalmars-d mailing list