D performance guideline (request)
Sean Kelly
sean at invisibleduck.org
Sat Apr 12 11:10:38 PDT 2008
== Quote from bobef (bobef at abv-nospam.bg)'s article
> Hi,
> I would like to request a guideline how to squeeze every last nanosecond out of D. I am writing this
scripting language - FlowerScript, and I really need to take every spare bit... But the problem is... I am a
noob. D performs really well, of course, but lame people like me could make even D slow :) I know here
are a lot of people that are very good programmers with broad knowledge how things work and a lot of
experiene, so I would like to ask you to share your experience - what to do when every tick matters. For
example one could use pointers for indexing arrays, to bypass the bounds checking. Yes, it is not that
pretty but gives a big boost. I am trying to experiment with things, but sometimes it is really strange.
For example I have few ifs. I rearrange them a bit. Sometimes I move one if inside other and it becomes
slower, sometimes I simply add curly braces and it becomes faster. Or I wrap a block of code in a try {}
and it becomes faster. Why is that? If I wrap every line of code in try, will I make it fly ? :D
The code generator used by DMD is really weird. Similar things cropped up during performance
tests of the Tango XML parser--sometimes just rearranging a set of declarations would have a
considerable effect on performance. I think a lot of it had to to with alignment and such. There's
generally no point in this level of optimization, because each compiler will react differently to the
changes. GDC, for example, tended to react in an opposite manner of DMD, though it was more
consistent overall.
As for performance tuning itself--don't worry about pointers vs. indexing. Using the -release
flag will turn off bounds checking anyway. Typically, the most notable effect you'll see is from
the overarching algorithms you use. However, if you're really counting cycles then you can do
things like minimize branches by placing the condition you expect to be true most often inside
an "if" statement. ie.
void func() {
if( x ) {
// A
return;
}
// B
}
With the above, A will be executed without any jumps, while execution will have to jump to
B to continue. If you expect x to almost always be true and the performance of func() is
crucial, consider writing it like the above instead of:
void func() {
if( !x ) {
// B
return;
}
// A
}
However, in general I suggest favoring readability over a nanosecond or two of performance
gain. There are other suggestions as well, but in general the 80-20 rule dictates that such
things should really only occur once your app is done and working, and then be tuned from
profiler results.
Sean
More information about the Digitalmars-d
mailing list