byte and short data types use cases

Basile B. b2.temp at gmx.com
Fri Jun 9 23:51:07 UTC 2023


On Friday, 9 June 2023 at 15:07:54 UTC, Murloc wrote:
> On Friday, 9 June 2023 at 12:56:20 UTC, Cecil Ward wrote:
>> On Friday, 9 June 2023 at 11:24:38 UTC, Murloc wrote:
>>
>> If you have four ubyte variables in a struct and then
>> an array of them, then you are getting optimal memory usage.
>
> Is this some kind of property? Where can I read more about this?

Yes, a classsic resource is 
http://www.catb.org/esr/structure-packing/

> So you can optimize memory usage by using arrays of things 
> smaller than `int` if these are enough for your purposes,

It's not for arrays, it's also for members

```d
struct S1
{
     ubyte a; // offs 0
     ulong b; // offs 8
     ubyte c; // offs 16
}

struct S2
{
     ubyte a; // offs 0
     ubyte c; // offs 1
     ulong b; // offs 8
}

static assert(S1.sizeof > S2.sizeof); // 24 VS 16
```

this is because you cant do unaligned reads for `b`, but you can 
for `a` and `c`.

> but what about using these instead of single variables, for 
> example as an iterator in a loop, if range of such a data type 
> is enough for me? Is there any advantages on doing that?

Not really the loop variable takes a marginal part of the stack 
space in the current function. You can just use `auto` and let 
the compiler choose the best type.




More information about the Digitalmars-d-learn mailing list