Optimizing delegates

Max Samukha spambox at d-coding.com
Sun Dec 19 08:46:46 PST 2010


On 12/19/2010 06:35 PM, Ary Borenszweig wrote:
> On 12/19/2010 01:21 PM, Andrei Alexandrescu wrote:
>> On 12/19/10 9:32 AM, Ary Borenszweig wrote:
>>> I have this code:
>>>
>>> ---
>>> import std.stdio;
>>>
>>> int foobar(int delegate(int) f) {
>>> return f(1);
>>> }
>>>
>>> int foobar2(string s)() {
>>> int x = 1;
>>> mixin("return " ~ s ~ ";");
>>> }
>>>
>>> void main() {
>>> writefln("%d", foobar((int x) { return 2*x; }));
>>> writefln("%d", foobar2!("9876*x"));
>>> }
>>> ---
>>>
>>> When I compile it with -O -inline I can see with obj2asm that for the
>>> first writefln the delegate is being called. However, for the second
>>> it just passes
>>> 9876 to writefln.
>>>
>>> From this I can say many things:
>>> - It seems that if I want hyper-high performance in my code I must use
>>> string mixins because delegate calls, even if they are very simple and
>>> the
>>> functions that uses them are also very simple, are not inlined. This
>>> has the drawback that each call to foobar2 with a different string
>>> will generate a
>>> different method in the object file.
>>
>> You forgot:
>>
>> writefln("%d", foobar2!((x) { return 2*x; })());
>>
>> That's a real delegate, not a string, but it will be inlined.
>>
>>
>> Andrei
>
> Sorry, I don't understand. I tried these:
>
> 1.
> int foobar3(int delegate(int) f)() {
> return f(1);
> }
>
> writefln("%d", foobar3!((int x) { return 2*x; })());
>
> => foo.d(12): Error: arithmetic/string type expected for
> value-parameter, not int delegate(int)

int foobar3(alias f)() {
     return f(1);
}

alias template parameters accept everything that variadic template 
parameters do (including delegate literals) with the unfortunate 
exception of basic types :-O.



More information about the Digitalmars-d mailing list