Optimizing delegates

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Dec 19 08:21:11 PST 2010


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


More information about the Digitalmars-d mailing list