Closures and memory allocation

kinke noone at nowhere.com
Sat Jun 22 19:50:13 UTC 2019


On Saturday, 22 June 2019 at 16:52:07 UTC, Anonymouse wrote:
> When entering the following function, does it allocate:
>
> 1. 0 times, because while there are closures defined, none is 
> ever called?
> 2. 2 times, because there are closures over two variables?
> 3. 20 times, because there are 20 unique closures?

4. One time, allocating a single closure for all variables 
referenced in nested functions. Easy to check by inspecting the 
generated asm (https://run.dlang.io/is/qO3JxO):

void receive(void delegate() a, void delegate() b) {}

void foo()
{
     int i;
     long l;

     void foo1() { i += 1; }
     void foo2() { l += 1; }

     receive(&foo1, &foo2);
}

When adding `scope` to the `receive()` params, the closure is 
allocated on the stack.


More information about the Digitalmars-d-learn mailing list