C++17 cannot beat D surely
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Tue Jun 6 18:09:25 PDT 2017
On 6/6/17 8:28 PM, Yuxuan Shui wrote:
> On Sunday, 4 June 2017 at 04:39:21 UTC, Adam D. Ruppe wrote:
>> On Sunday, 4 June 2017 at 04:34:44 UTC, Mike Parker wrote:
>>> I would not have expected enum b = sort(a) to trigger an allocation.
>>> auto b, yes, of course (and the disassembly from that is not much
>>> different). So I'd love to see a blog post explaining it.
>>
>> I don't think I can do a full-on blog post, but I can answer it in a
>> couple sentences: `enum` is treated by the compiler just like
>> literals. Array literals allocate at each usage point, therefore enum
>> arrays allocate at each usage point. (*each* usage point)
>
> I think the allocation is because sort returns a SortedRange, not an array.
>
> So even this allocates:
>
> enum b = a.sort;
> writeln(b[1]);
>
> OTOH, this doesn't allocate:
>
> enum b = a.sort.array;
> writeln(b[1]);
I think it's because the compiler isn't smart enough to pull out the
allocation for SortedRange!(...)([0,1,2,3,4])[1], but it is smart enough
to know that [0,1,2,3,4][1] does not need to allocate.
But it is pretty well known that enum'ing an array can have it allocate
wherever it is used.
For example, if you do this:
enum b = a.sort.array;
auto c = b;
It will allocate.
If you do:
auto d = b;
It will allocate again.
That is an interesting artifact though. Another good reason to use static.
-Steve
More information about the Digitalmars-d
mailing list