Delegate Memory Usage & Optimization

Manu turkeyman at gmail.com
Wed Dec 11 20:16:08 PST 2013


On 12 December 2013 14:06, Manu <turkeyman at gmail.com> wrote:

> On 12 December 2013 13:45, Maxime Chevalier-Boisvert <
> maximechevalierb at gmail.com> wrote:
>
>> It only allocates a closure if (1) it thinks the delegate may escape the
>>> scope and (2) uplevel references are used in the delegate.
>>>
>>
>> The delegate will escape the enclosing scope. I'm wondering if there will
>> still be some kind of scope object allocated to represent escaping values
>> in the englobing stack frame, even when there are no escaping values.
>>
>> I don't mind paying the small cost of an extraneous null context pointer,
>> but having a whole unnecessary context object allocated seems wasteful.
>
>
> If you have no use for the context pointer, then it sounds like what you
> want is a function pointer, not a delegate.
>
> A delegate is just a function-ptr+context-ptr pair, it is a trivial struct
> that is passed by value, the same as a dynamic array. The context pointer
> may be to a stack frame (in case of a closure), or a class object (in the
> case of a class method pointer).
> If you intend a null context pointer (ie, function doesn't reference any
> state), than what you really have is a function pointer, not a delegate.
> You should use a function pointer instead.
>

Oh sorry, I see. you just mean in some cases functions that don't access
state will be bound to your delegate.
It seems unusual to me for a function that doesn't access any state to
produce a delegate. Wouldn't it be static, or a free function in that case?

There are tricks to bind a free function to a delegate using a little
call-through stub. It sets the delegate function to a callthrough-stub
which internally casts 'this' to a 'function' and calls it with the same
arguments.
Don does it to bind static functions to delegates in his C++ FastDelegate
library. I wonder if there's a helper in phobos?
You can be sure when assigning functions to delegates in this way that
there will never be any associated state.

Can you show your usage?
>
>  I strongly suggest trying out a couple examples, and disassembling the
>>> result to confirm.
>>>
>>
>> I'll look into that.
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20131212/7327562c/attachment.html>


More information about the Digitalmars-d mailing list