Fake infix operators

downs default_357-line at yahoo.de
Mon Oct 29 06:23:24 PDT 2007


Bill Baxter wrote:
> 
> Does it compile down to the same code as just a plain call to a map()
> function?  (Or is there some other benefit that justifies the extra
> runtime cost and loss of readability?)
> 
> --bb

Loss of readability is debatable. Personally I like it better, or else I
wouldn't use it. :)
The runtime cost might not be as high as you expect. Let us do a test.

>
> module test12;
> import std.stdio;
> import tools.base, tools.functional, tools.log;
>
> int add(int a, int b) { return a+b; }
>
> mixin(Operator!("add3", "return lhs+rhs;"));
>
> void main() {
>   const long count=1_000_000_000;
>   long test;
>   int delegate(int, int) add1=(int a, int b) { return add(a, b); };
>   int function(int, int) add2=&add;
>   logln("Function: ", time({ for (int i=0; i<count; ++i) test+=add(0,
1); }), " -test ", test);
>   logln("Delegate function: ", time({ for (int i=0; i<count; ++i)
test+=add1(0, 1); }), " -test ", test);
>   logln("Function ... function: ", time({ for (int i=0; i<count; ++i)
test+=add2(0, 1); }), " -test ", test);
>   logln("Infix function: ", time({ for (int i=0; i<count; ++i) test+=0
/add3/ 1; }), " -test ", test);
> }
>

The results:

> gentoo-pc ~/d $ gdc test12.d -o test12 -O3 -frelease -Itools
tools/tools/*.d && ./test12
> /--[ Main Thread ]------
> | Function: 0 -test 1000000000
> | Delegate function: 7234 -test 2000000000
> | Function ... function: 6415 -test -1294967296
> | Infix function: 1501 -test -294967296
> \-----------------------------
>

Hm ... interesting.
I had expected the infix function to be inlined as well as the straight
function. Ah well. Four times the speed of an un-inlined function is
good enough for me. :)



More information about the Digitalmars-d mailing list