Inside the switch statement

Kagamin spam at here.lot
Thu Jun 11 05:55:58 PDT 2009


> template duffs_device(alias id1, alias id2, alias s)
> {
>     void duff_loop()
>     {
> 	if (id1 < id2)
> 	{
> 	    typeof(id1) n = (id2 - id1 + 7) / 8;
> 	    switch ((id2 - id1) % 8)
> 	    {
> 		case 0:        do {  s();
> 		case 7:              s();
> 		case 6:              s();
> 		case 5:              s();
> 		case 4:              s();
> 		case 3:              s();
> 		case 2:              s();
> 		case 1:              s();
> 				  } while (--n > 0);
> 	    }
> 	}
>     }
> }
> 
> void foo() { writefln("foo"); }
> 
> void test()
> {
>     int i = 1;
>     int j = 11;
> 
>     mixin duffs_device!(i, j, delegate { foo(); } );
>     duff_loop();	// executes foo() 10 times
> }

The Duff's device is said to be an optimization, but I get blunt device only 0.7% slower.

template blunt_device(alias id1, alias id2, alias s)
{
	void blunt_loop()
	{
		if (id1 < id2)
		{
			typeof(id1) i = id2 - id1;
			while(i-->0)s();
		}
	}
}



More information about the Digitalmars-d-learn mailing list