May 14, 2017
On Sunday, 14 May 2017 at 11:45:12 UTC, ag0aep6g wrote:
> On 05/14/2017 01:40 PM, Nicholas Wilson wrote:
>> dynamic array literals is what I meant.
>
> I don't follow. Can you give an example in code?

void main()
{
    ubyte[] arr = [ 1, 2, 3, 4, 5 ];

    assert(arr == [ 1, 2, 3, 4, 5 ]);
}

Both, assignment and comparison, allocate.
May 14, 2017
On 05/14/2017 02:02 PM, Eugene Wissner wrote:
> void main()
> {
>     ubyte[] arr = [ 1, 2, 3, 4, 5 ];
>
>     assert(arr == [ 1, 2, 3, 4, 5 ]);
> }
>
> Both, assignment and comparison, allocate.

Sure, but Nicholas said 1D arrays behave different from 2D arrays.
May 14, 2017
On Sunday, 14 May 2017 at 12:02:03 UTC, Eugene Wissner wrote:
> On Sunday, 14 May 2017 at 11:45:12 UTC, ag0aep6g wrote:
>> On 05/14/2017 01:40 PM, Nicholas Wilson wrote:
>>> dynamic array literals is what I meant.
>>
>> I don't follow. Can you give an example in code?
>
> void main()
> {
>     ubyte[] arr = [ 1, 2, 3, 4, 5 ];
>
>     assert(arr == [ 1, 2, 3, 4, 5 ]);
> }
>
> Both, assignment and comparison, allocate.

LDC is able to promote those to alloca, not sure about DMD or its interaction with @nogc.
see https://github.com/ldc-developers/ldc/blob/master/gen/passes/GarbageCollect2Stack.cpp#L832 for the details.
May 15, 2017
On 5/14/17 7:40 AM, Nicholas Wilson wrote:
> On Sunday, 14 May 2017 at 10:18:40 UTC, ag0aep6g wrote:
>> On 05/14/2017 01:57 AM, Nicholas Wilson wrote:
>>> 1D arrays it doesn't, 2D or higher it does.
>>
>> What do you mean? This works just fine as well:
>>
>> ----
>> import std.random;
>> import std.stdio;
>>
>> int[2][2] testfunc(int num) @nogc
>> {
>>     return [[0, 1], [num, 3]];
>> }
>>
>> int main()
>> {
>>     int[2][2] arr = testfunc(uniform(0, 15));
>>     writeln(arr);
>>     return 0;
>> }
>> ----
>
> dynamic array literals is what I meant.

dynamic array literals allocate most of the time. The one time they don't is the specialized case of initializing a static array, I think of any dimension.

However, to the OP's point, they *did* allocate up until a certain version, even when initializing a static array.

That is:

int[2] x = [1, 2];

used to allocate a dynamic array on the heap, and then copy the data into x (and leave the allocated data for the GC). Now it just populates x without allocating.

LDC might be smarter, and take more valid shortcuts, so that is good. But in general you can expect array literals to allocate when not used as static array initializers.

-Steve
1 2
Next ›   Last »