Collections expression to add an item at the start.
I've got this:
What I intend for it to do is to return an array of uints which starts with zero as the first value, then appends the contents of
Colors
(another array of uint
) up to a maximum of 255 items, so that this array can never be larger than 256 items.
This expression I've got appears to work, technically, but it also appears that I should be able to do this without creating a new List<uint>
just to add that one item. I'm almost certian there's some expression I could include which wouldn't require that. Anyone know?16 Replies
I wonder if
[0u, ..Colors[..255]]
is efficientthe most efficient is
does mine actually copy Colors first before making the end result array?
yes
ugh
I expect it to be making a copy.
no, it's a useless copy
extra unnecessary copy
Oh why useless
it copies the first 255 elements of
Colors
into a new uint[]
, then it copies that uint[]
into the 256-element uint[]
that you are returning
the AsSpan avoids the first copy, it will copy directly from one array to the one you returnI should mention that this is inside of a
readonly record struct
so Colors shouldn't be monkeyed with
Oh nice.
Wait, there is no guarantee that colors will have 255 items
It could be empty or could have up to 255 itemsColors.AsSpan(0, int.Min(255, Colors.Length))
oh that's better, thanks
I ended up with
seems fine
I'm still getting used to collections syntax. Thanks.