Array concatenation & optimisation

Nick Treleaven nick at geany.org
Sun Jul 21 10:33:38 UTC 2024


On Sunday, 21 July 2024 at 05:43:32 UTC, IchorDev wrote:
> Obviously when writing optimised code it is desirable to reduce 
> heap allocation frequency. With that in mind, I'm used to being 
> told by the compiler that I can't do this in `@nogc` code:
> ```d
> void assign(ref int[4] a) @nogc{
> 	a[] = [1,3,6,9]; //Error: array literal in `@nogc` function 
> `assign` may cause a GC allocation
> }
> ```

Just to mention that if you assign to the static array it works: 
`a = [1,3,6,9];`.

>> 'may cause' a GC allocation
>
> Does this mean that array literals are *always* separately 
> allocated first, or is this usually optimised out?

My understanding is that they do not allocate if used to 
initialize or assign a static array. That includes passing an 
array literal as an argument to a static array function parameter.

A scope slice can also be initialized from an array literal in 
@nogc code:
https://dlang.org/changelog/2.102.0.html#dmd.scope-array-on-stack

But assigning a literal to a scope slice is not allowed in @nogc 
code.

> For instance, will this example *always* allocate a new dynamic 
> array for the array literal, and then append it to the existing 
> one, even in optimised builds?
> ```d
> void append(ref int[] a){
> 	a ~= [5, 4, 9];
> }
> ```

If there is enough spare capacity in a's allocation, no 
allocation will occur.

> Obviously for a long array literal, the benefit of knowing its 
> length upfront (and the readability) would probably outweigh 
> the allocation; but for small array literals, is splitting them 
> into separate concatenations going to yield faster code, or 
> will I waste my time and screen space?

Note that concatenation always allocates:

> Concatenation always creates a copy of its operands, even if 
> one of the operands is a 0 length array

https://dlang.org/spec/arrays.html#array-concatenation

> P.S. I am mostly addressing LDC2 & GDC's output, since I am 
> aware that DMD's optimisations are usually minimal.

While people may say that on the forum, dmd's optimizer does 
actually do data flow analysis:
https://forum.dlang.org/post/uqhgoi$31a7$1@digitalmars.com


More information about the Digitalmars-d-learn mailing list