delegates and heap usage

Simen kjaeraas simen.kjaras at gmail.com
Wed Dec 1 05:18:47 PST 2010


Franciszek Czekala <home at valentimex.com> wrote:

> What part of stack frame is exactly copied when a delegate is used?

Generally, only the used variables.

You can check the size of the closure's stack copy using
GC.sizeOf(dg.ptr).


> For example what is the heap usage due to delegates usage in the
> following code?

Adding this code to the end of it:

   int n = 0;
   void* ptr = null;
   foreach ( e; dlg ) {
     if ( e.ptr != ptr ) {
       ptr = e.ptr;
       n += GC.sizeOf( e.ptr );
     }
   }
   writeln( n );


We can see that 1600 bytes are used.

> The library reference speaks about the enclosing function but I do not  
> think
> that it suffices to copy the stack frame of the directly enclosing  
> function.
> Is the whole stack copied?

All enclosing functions need to have their stack frames copied. That is,
not the whole stack, but any functions for which the delegate would be a
nested function.


> What happens in the case of recursive calls?

int recurse( int delegate() dg ) {
     int n = 1;
     return GC.sizeOf( dg.ptr ) + ( dg() ? recurse( { return dg() - n; } )  
: 0 );
}

void main(){
     writeln( recurse( { return 100; } ) );
}

Outputs 1600.

-- 
Simen


More information about the Digitalmars-d mailing list