1) In the first example, a nit-pick. From the compiler's point of view, alignment will be a power of 2. Like 1, 2, 4, 8, ... etc. The compiler will add internal padding or trailing padding to the structure to satisfy the alignment. i.e. a structure size of 40 bytes satisfies an alignment of 8.
2) Wasted space actually may be more since alignment rules may be different depending on if it is an array or not. For example, if I allocate 2 separate variables, fbc-win-64bit, even though sizeof(Rect_t) is 40, I get 48 bytes between allocations for this structure because data alignment is 16. +1 for promoting thoughtful use of datatypes!
Code: Select all
'' default data alignment for types in arrays
'' is next power of 2 greater than or equal
'' than largest element.
Type Rect_t
As Integer _x, _y, _w, _h
As ULong _c
End Type
'' on 64-bit, alignment is 8 bytes due to
'' sizeof(integer) = 8, and results in structure size
'' of 40 bytes, which satisfies alignment = 8
dim a(0 to 1) as Rect_t
print "Rect_t(): " & cint(@a(1)) - cint(@a(0)) '' 40
'' if not in an array, alignment might be larger,
'' like 16 bytes, resulting in 48 bytes between
'' allocations
dim as Rect_t b1, b2
print "Rect_t: " & cint(@b2) - cint(@b1) '' 48
3) Sorry, your optimized example is lost on me. For each small structure, a pointer is allocated, plus are at the mercy of alignment of the memory allocator (NEW). On fbc-win-64bit 8 bytes per pointer plus 32 bytes per NEW, so 40 bytes per total per "small" structure. On fbc-win-32bit, 4 bytes per pointer plus 16 bytes per "NEW Rect_t", Results will vary by platform. Plus, no ability to store x,y,colour in the structure. ??
Code: Select all
'' using new/delete and pointers
Type Small_Rect_t
As ushort _w, _h
End Type
dim c1 as Small_Rect_t ptr = new Small_Rect_t
dim c2 as Small_Rect_t ptr = new Small_Rect_t
dim c3 as Small_Rect_t ptr = new Small_Rect_t
dim c4 as Small_Rect_t ptr = new Small_Rect_t
print "Small_Rect_t: " & cint(c2) - cint(c1) '' 112
print "Small_Rect_t: " & cint(c3) - cint(c2) '' 32
print "Small_Rect_t: " & cint(c4) - cint(c3) '' 32
delete c4
delete c3
delete c2
delete c1