The future of lambda delegates

BCS BCS at pathlink.com
Wed Aug 16 11:47:36 PDT 2006


Walter Bright wrote:
> Mikola Lysenko wrote:
> 
>> Such a translation is possible for any of these examples, albeit quite 
>> tedious.  From what I gather C# applies a similar technique with its 
>> lambda delegates and inner classes.  For a machine code compiler, such 
>> a rewrite is not even necessary, since it could simply overwrite the 
>> frame pointer at the start of the function with a GC allocated block.  
>> This would preserve frame-based addressing for arguments and 
>> variables, requiring no change in any of the internally generated 
>> machine code.  The run time overhead is fairly low, only on the order 
>> of one extra memory allocation per function call.  Practically, such 
>> an implementation would be extremely simple.
>>
>> Any thoughts or comments?
> 
> 
> Yes, I'm aware of this, and want to fix it for D 2.0. The way to fix it 
> is, as you suggest, allocating the frame on the heap rather than on the 
> stack. The drawback with that is that heap allocation is far, far more 
> expensive than stack allocation.

because this is so much slower, I would hate to see it happen silently. 
Having a function use a heap-frame just because I add a delegate could 
cause some hard to track down performance hits. I would advocate making 
the escaping delegate illegal unless the code explicitly says to put 
/part/ or all of the frame on the heap.

> 
> An ideal solution would be if the compiler could statically detect if a 
> nested class reference can 'escape' the stack frame, and only then 
> allocate on the heap. Otherwise, the current (very efficient) method of 
> just passing a frame pointer would be employed.
> 




BTW how do you construct a delegate literal inside of a class method 
that uses "this" as it's context, rather than the frame pointer?

class Foo
{
	int i;
	int delegate() fig(){ return {return i;}; }
//	int delegate() fig(){ return this.{return i;}; }  // this maybe?
}

void main()
{
	auto foo = new Foo;
	auto farm = foo.fig;

	foo.i = 5;
	auto i = farm(); // valid if context is "foo"
	assert(i == 5);
}



More information about the Digitalmars-d mailing list