Array concatenation & optimisation

IchorDev zxinsworld at gmail.com
Sun Jul 21 05:43:32 UTC 2024


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
}
```
> 'may cause' a GC allocation

Does this mean that array literals are *always* separately 
allocated first, or is this usually optimised out?
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];
}
```
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?

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


More information about the Digitalmars-d-learn mailing list