C
C#2y ago
Stroniax

✅ Struct Fields

Is there a reason to mask two values into a single field on a struct, e.g. if I want a struct MyValue with fields ushort A and ushort B, is there any value in having the struct internally store the value as uint _c? I formerly thought since this was one field it was better because everyone says to generally not use a struct with a lot of fields, but based on some reading I have done it seems that maybe this is treated in memory the same way since those two ushort fields are side-by-side and effectively storing two ushort fields would be no different except that I wouldn't have to manually unmask A and B from _c in my getters.
7 Replies
Anton
Anton2y ago
my guess is that it will perform the same, but you should benchmark it
Akseli
Akseli2y ago
there is no value storing 2 side by side ushorts in an uint because they consume the same amount of memory and are both properly aligned the "dont use a struct with a lot of fields" doesnt matter in this case the amount of fields doesnt really matter, the size of the struct matters more, for example 16x byte fields technically would be fine because it only consumes 16 bytes of memory generally you should keep struct size max 16 bytes
Stroniax
StroniaxOP2y ago
Because that is the size of nint?
Sossenbinder
Sossenbinder2y ago
IIRC it's a pretty arbitrary number which materialized itself as a good rough idea of the size after which a struct might end up performing worse Due to copying by value instead of reference
Anton
Anton2y ago
and if you pass structs around by reference, it doesn't mean anything
Sossenbinder
Sossenbinder2y ago
Indeed So it's just a rough estimate mostly
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server