C++17 cannot beat D surely
Mike Parker via Digitalmars-d
digitalmars-d at puremagic.com
Sat Jun 3 21:34:44 PDT 2017
On Sunday, 4 June 2017 at 03:28:32 UTC, Andrei Alexandrescu wrote:
> On 06/03/2017 07:41 PM, jmh530 wrote:
>> On Saturday, 3 June 2017 at 22:18:06 UTC, Timon Gehr wrote:
>>>
>>> There is no mistake. (But 'auto' is redundant.)
>>>
>>>> void main() {
>>>> import std.algorithm, std.stdio;
>>>> enum a = [ 3, 1, 2, 4, 0 ];
>>>> enum b = sort(a);// static is not CT !!!!!
>>>> static assert(b[0] == 0); // does not pass with static
>>>> auto b...
>>>> writeln(b);
>>>> }
>>>>
>>>>
>>>
>>> This is worse. Now there is an allocation at runtime.
>>
>> So maybe we can do a blog post on when to use static or enum?
>> Because smart people don't seem to be agreeing on this...
>
> Yes please! cc Mike. -- Andrei
Any volunteers? This one surprised me.
Looking at the disassembly over at godbolt, I see this when using
enum b = sort(a):
```
lea rax, [rbp-64]
mov QWORD PTR [rax], 0
mov QWORD PTR [rax+8], 0
mov QWORD PTR [rbp-48], 0
mov QWORD PTR [rbp-40], 0
mov DWORD PTR [rbp-32], 0
mov DWORD PTR [rbp-44], 1
mov DWORD PTR [rbp-40], 2
mov DWORD PTR [rbp-36], 3
mov DWORD PTR [rbp-32], 4
mov esi, 5
mov edi, OFFSET FLAT:_D11TypeInfo_Ai6__initZ
call _d_arrayliteralTX
mov rdx, QWORD PTR [rbp-48]
mov QWORD PTR [rax], rdx
mov rdx, QWORD PTR [rbp-40]
mov QWORD PTR [rax+8], rdx
mov edx, DWORD PTR [rbp-32]
mov DWORD PTR [rax+16], edx
mov QWORD PTR [rbp-64], 5
mov QWORD PTR [rbp-56], rax
mov rax, QWORD PTR [rbp-64]
mov rdx, QWORD PTR [rbp-56]
mov rcx, rax
mov rbx, rdx
mov rax, rdx
mov rdi, rcx
mov rsi, rax
call writeln
```
And this when using static b = sort(a) (and the same with static
immutable b):
```
mov rdx, QWORD PTR fs:std.range.SortedRange!(int[], "a <
b").SortedRange
example.main().b at tpoff
mov rax, QWORD PTR fs:std.range.SortedRange!(int[], "a <
b").SortedRange
example.main().b at tpoff+8
mov rdi, rdx
mov rsi, rax
call writeln
```
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.
More information about the Digitalmars-d
mailing list