On Thu, 13 May 2010 22:38:40 -0400, kai <k...@nospam.zzz> wrote:

Hello,

I was evaluating using D for some numerical stuff. However I was surprised to
find that looping & array indexing was not very speedy compared to
alternatives (gcc et al). I was using the DMD2 compiler on mac and windows,
with -O -release. Here is a boiled down test case:

        void main (string[] args)
        {
                double [] foo = new double [cast(int)1e6];
                for (int i=0;i<1e3;i++)
                {
                        for (int j=0;j<1e6-1;j++)
                        {
                                foo[j]=foo[j]+foo[j+1];
                        }
                }
        }

Any ideas? Am I somehow not hitting a vital compiler optimization? Thanks for
your help.

I figured it out.

in D, the default value for doubles is nan, so you are adding countless scores of nan's which is costly for some reason (not a big floating point guy, so I'm not sure about this).

In C/C++, the default value for doubles is 0.

BTW, without any initialization of the array, what are you expecting the code to do? In the C++ version, I suspect you are simply adding a bunch of 0s together.

Equivalent D code which first initializes the array to 0s:

void main (string[] args)
{
    double [] foo = new double [cast(int)1e6];
    foo[] = 0; // probably want to change this to something more meaningful
    for (int i=0;i<cast(int)1e3;i++)
    {
        for (int j=0;j<cast(int)1e6-1;j++)
        {
            foo[j]+=foo[j+1];
        }
    }
}

On my PC, it runs almost exactly at the same speed as the C++ version.

-Steve

Reply via email to