Hello!

First my background: C++ and Java ages ago. Since then only PLSQL. Now learning D just for fun and personal education on time to time and very pleased about it :-)

Now I have to ask a question here, because I could not find a corresponding answer for it. Or I am unable to find it :-)

I was wondering about the memory system in D (and other C like languages) about the handling of the memory allocation overhead.

Just an example that I have seen many times:


int main()
{
    foreach(i;0 .. 10000)
    {
        int x;
        // do something with x
    }
    return 0;
}


Do I understand it right that the variable x will be created 10000 times and destroyed at the end of the scope in each loop ? Or will it be 10000 overwritten by creation ? I mean does it not cost the CPU some time to allocate (I know were talking here of nsec) but work is work. As far I know from my school days in assembler, allocation of memory is one of the most expensive instructions on the cpu. Activate memory block, find some free place, reserve, return pointer to caller, and so on..

In my opinion this version should perform a little better:

int main()
{
    int x;
    foreach(i;0 .. 10000)
    {
        x = 0; // reinitialize
        // do something with x
    }
    return 0;
}

Or do I miss something and there is an optimization by the compiler to avoid recreating/destroying the variable x 10000 times ?

I know that version 1 is more secure because there will be no value waste after each loop we could stumble onto, but that is not my question here. And I know that were talking about really small cpu usage compared to what an app should do. But when it is to look on performance like games or gui (and there are a lot of examples like version 1 out there) then I have to ask myself if it is not just a waste of cpu time ?

Or is it a styling of code thing ?

Thank you for your time!


Greetings from Austria
Thomas

Reply via email to