Optimizing for specific object types

downs default_357-line at yahoo.de
Fri Jul 18 15:00:20 PDT 2008


The following mixin code can be used to generate optimized code for specific, final types automatically.

This can really speed up some inner loops if used carefully. It allows the compiler to inline at the cost of one dynamic cast.

import std.stdio;

string repl(string text, string what, string by) {
  string res;
  int i;
  while (i + what.length !> text.length) {
    if (text[i .. i+what.length] == what) {
      res ~= by;
      i += what.length;
    } else {
      res ~= text[i];
      i ++;
    }
  }
  res ~= text[i .. $];
  return res;
}

static assert(repl("foobarfobes", "ob", "kn") == "foknarfknes");

template ExpectCall(string VAR, string OP, TYPES...) {
  static if (!TYPES.length)
    const string ExpectCall = repl(OP, "$$", VAR)~"; ";
  else
    const string ExpectCall = "if (auto ec_var = cast("~TYPES[0]~") "~VAR~") {
  "~repl(OP, "$$", "ec_var")~";
} else {
  "~ExpectCall!(VAR, OP, TYPES[1 .. $])~"
}";
}

class A { void test() { writefln("test A"); } }
final class B : A { void test() { writefln("test B"); } }
final class C : A { void test() { writefln("test C"); } }

void main() {
  A[] foo = [new A, new B, new C];
  pragma(msg, ExpectCall!("entry", "$$.test()", "B", "C"));
  foreach (entry; foo) {
    mixin(ExpectCall!("entry", "$$.test()", "B", "C"));
  }
}



More information about the Digitalmars-d mailing list