Delegate perfomance (outrage was redherring)
bearophile
bearophileHUGS at lycos.com
Thu Oct 15 23:53:39 PDT 2009
Justin Johansson:
> this turns out to be
> a clear demonstration of the performance-enhancing power of D delegates over an
> otherwise ingrained C++ thinking approach.
I have changed your benchmark a little, you may want to look at its timings too (I have taken timings with it with DMD and LDC, and the results differ):
version (Tango) {
import tango.stdc.stdio: printf;
import tango.stdc.time: CLOCKS_PER_SEC, clock;
} else {
import std.c.stdio: printf;
import std.c.time: CLOCKS_PER_SEC, clock;
}
double myclock() {
return clock() / cast(double)CLOCKS_PER_SEC;
}
abstract class Visitor {
//interface Visitor { // try this too
abstract int visit(int x);
}
final class MyVisitor: Visitor {
int visit(int x) { return 0; }
}
struct IntRange {
int stop;
int forEachDeleg(int delegate(int x) apply) {
for (int i; i < stop; i++)
apply(i);
return 0;
}
int forEachObj(Visitor v) {
for (int i; i < stop; i++)
v.visit(i);
return 0;
}
}
void testD(IntRange s, Visitor v) {
auto start = myclock();
s.forEachDeleg(&v.visit);
auto stop = myclock();
printf("Using D style delegate callback: %d ms\n", cast(int)((stop - start) * 1000));
}
void testCpp(IntRange s, Visitor v) {
auto start = myclock();
s.forEachObj(v);
auto stop = myclock();
printf("Using C++ style virtual callback: %d ms\n", cast(int)((stop - start) * 1000));
}
void main() {
auto s = IntRange(400_000_000);
Visitor v = new MyVisitor();
for (int i; i < 5; i++) {
testD(s, v);
testCpp(s, v);
printf("\n");
}
}
(I suggest you to use the _ inside big number literals in D, they avoid few bugs).
(Few days ago I think to have found that interfaces aren't implemented efficiently in LDC. Lindquist has answered he will improve the situation.)
Bye,
bearophile
More information about the Digitalmars-d
mailing list