Array concatenation & optimisation

IchorDev zxinsworld at gmail.com
Sun Jul 21 16:04:56 UTC 2024


On Sunday, 21 July 2024 at 10:33:38 UTC, Nick Treleaven wrote:
> Just to mention that if you assign to the static array it 
> works: `a = [1,3,6,9];`.

Bonkers. `array[]` is meant to be 'all of `array` as a slice', so 
you'd think that's how you copy a slice to a static array, but no!

> 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.

D is pretty eager to make array literals into slices; thus have I 
developed a general distrust for using array literals in the 
vicinity of static arrays.

Case and point:

> 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.


> 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

Thank you for all this info!

>> 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

People frequently come here to complain that 'D is slow' when 
they're using DMD, and often not even using `-O`. The responses 
will then usually contain some version of 'don't use DMD to 
generate optimised code'.


More information about the Digitalmars-d-learn mailing list