Performance of loops

Chris via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 24 07:13:01 PDT 2015


On Friday, 24 April 2015 at 13:55:49 UTC, Steven Schveighoffer 
wrote:
> On 4/24/15 9:13 AM, Chris wrote:
>> On Friday, 24 April 2015 at 11:53:56 UTC, Marc Schütz wrote:
>>> Most of the time is taken up by the array's allocation. The 
>>> optimizers
>>> of both DMD and LDC evidently doesn't optimize it away when 
>>> you use
>>> `ref`, even though it could in theory.
>>>
>>> Remove the `enum` and just use a normal global variable, and 
>>> you will
>>> get more or less identical times for all three loops. LDC 
>>> even turns
>>> then into empty functions (didn't check for DMD).
>>
>> I've tried it, and the loops indeed show similar results. What 
>> is it
>> about `enum` that slows it down?
>
> enum of an array literal is like pasting the array literal 
> wherever the enum lives.
>
> So for example, your const loop:
>
> void constLoop() {
>   size_t cnt;
>   foreach (const ref w; words)
>     cnt += w.length;
> }
>
> Is really like saying:
>
> void constLoop() {
>   size_t cnt;
>   foreach (const ref w; ["Hello", "world", "Ola", "mundo"])
>     cnt += w.length;
> }
>
> And note that in D right now, an array literal is NOT stored in 
> the data segment. It's generated every time you use it (with a 
> call to _d_newarray, which allocates on the GC).
>
> There was a push a while back to make array literals immutable 
> and placed in the data segment. But it never panned out, would 
> break too much code.
>
> -Steve

Thanks for the clarification.


More information about the Digitalmars-d mailing list