class templates and static if

Ali Çehreli acehreli at yahoo.com
Wed Feb 29 11:09:42 PST 2012


On 02/28/2012 02:12 AM, Dmitry Olshansky wrote:
 > On 28.02.2012 2:17, Ali Çehreli wrote:

 >> I have played with this optimization recently. (Could be dmd 2.057.) No,
 >> dmd did not optimize a straightforward switch statement over a ubyte
 >> expression with about two hundred ubyte cases.
 >>
 > Hate to say it but I see it in real-world code, VM performance almost
 > doubled.

That's really good to hear. Perhaps my experiments were either naive, or 
a series of "cmp xxx je xxx" would be faster, say for the ubyte type 
that I've used.

 > Mm care to share you experiments?

Here is a program that mixes-in a lookup function that contains a single 
switch statement that covers the entire 256 values of ubyte:

import std.stdio;
import std.conv;

string oneCase(FromT, ToT)(FromT fromExpr, ToT toExpr)
{
     return
         " case " ~ to!string(fromExpr)
         ~ ": return " ~ to!string(ToT.init) ~ "; ";
}

string manyCases(FromT, ToT)(size_t count)
{
     string result;

     ToT fromExpr;
     foreach (i; 0 .. count) {
         result ~= oneCase(fromExpr, 42);
         ++fromExpr;
     }

     return result;
}

string lookUpFunc(FromT, ToT)(size_t count)
{
     immutable header = ToT.stringof ~ " lookUp(" ~ FromT.stringof
                        ~ " expr) { switch (expr) { ";
     immutable cases = manyCases!(FromT, ToT)(count);
     immutable footer = " default: return " ~ to!string(ToT.init) ~ "; } }";

     return header ~ cases ~ footer;
}

void main()
{
     enum funcWithManyCases = lookUpFunc!(ubyte, ubyte)(256);

     writeln("Mixing-in: ", funcWithManyCases);
     mixin(funcWithManyCases);

     assert(lookUp(42) == 0);
}

I compiled with -O and then used obj2asm to see that there are 256 cmp 
xxx jmp xxx instructions.

Ali



More information about the Digitalmars-d-learn mailing list