Dynamic Closure + Lazy Arguments = Performance Killer?

Denis Koroskin 2korden at gmail.com
Sat Oct 25 11:04:47 PDT 2008


On Sat, 25 Oct 2008 21:17:34 +0400, Frits van Bommel  
<fvbommel at remwovexcapss.nl> wrote:

>> On Sat, Oct 25, 2008 at 10:44 AM, Denis Koroskin <2korden at gmail.com>  
>> wrote:
>>> I also think that scope and heap-allocated delegates should have  
>>> different
>>> types so that no imlicit casting from scope delegate to heap one would  
>>> be
>>> possible. In this case callee function that recieves the delegate might
>>> demand the delegate to be heap-allocated (because it stores it, for
>>> example).
>
> How would this work? For example:
> -----
> struct Struct {
>      // fields...
>
>      void foo() {
>          // body
>      }
> }
>
> void bar(Struct* p) {
>      auto dg = &p.foo;	// stack-based or heap-based delegate?
>      // do stuff with dg
> }
> -----
> ?

Good question! First, let's expand the code:

void bar(Struct* p) {

     void delegate() dg;

     dg.ptr = p;
     dg.funcptr = &Struct.foo;

     // do stuff with dg
}

So, here is the question: is this a "stack-based or heap-based delegate?"  
I.e. may we return it from function and pass it to those functions that  
need heap-base delegate or not?

Yes, we may return it, obviously, and call outside of the function, so  
 from this point of view it is indeed "heap-allocated delegate" even if  
nothing is actually allocated. But someone might say that it is unsafe to  
call this dg because at some point object may become inexistant. To  
respond this, let's rewrite the code to make it trully heap-allocated and  
compare if it got any safer:

void bar(Struct* p)
{
     void foo()
     {
         p.foo();
     }

     auto dg = &foo;
}

Now dg is heap-allocated (in the sense that place for its local variable  
are allocated on heap). May we return this delegate from function? Yes. Is  
it any safer? No. They are absolutely the same.

>      auto dg = &p.foo;	// stack-based or heap-based delegate?

Heap-based one, even if no actual allocation took place.



More information about the Digitalmars-d mailing list