r/cprogramming • u/EatingSolidBricks • Jan 29 '26
Given a choice when allocating a Fat pointer is it more optimal to A: have the metadata behind the pointer or B: on the stack
A:
Slice *slice = alloc(a, sizeof(*slice) + len*element_size);
slice->len = len*element_size;
slice->data = slice + 1;
B:
Slice slice = {0};
slice.len = len*element_size;
slice.data = alloc(a, len*element_size);Im most likely gonna be using Arenas for lifetime managment.
3
Upvotes
5
u/zhivago Jan 29 '26
The optimal solution is to have the user decide how to allocate it.
2
u/EatingSolidBricks Jan 29 '26 edited Jan 29 '26
It looks like Option A is marginally faster, I'm testing on slices of size INT32_MAX
compiled with clang -O3
It has no statistical differences on small slices
2
u/EatingSolidBricks Jan 29 '26
Or C: it dosent matter at all and im overthinking it?
1
u/EatingSolidBricks Jan 29 '26
If anyone wants to see the code (its upside down ...)
I allocate both slices beforehand since im only interested on the memory access pattern
1
u/Plane_Dust2555 Jan 29 '26
What is a "fat pointer"?
1
u/flyingron Jan 29 '26
What is alloc()? What is a?
1
u/Background-Glove8277 Jan 29 '26
“More optimal“, as in “more pregnant“?
1
u/[deleted] Jan 29 '26
Use flexible array member.
1
u/Afraid-Locksmith6566 Jan 29 '26
or D: fuc&ing measure
1
u/WittyStick Jan 29 '26
Fat pointer if struct it is <= 16-bytes as it will be passed and returned in hardware registers on 64-bit SYSV.
Larger than 16-bytes get put on the stack, so will incur a double dereference. Better to use an opaque pointer in this case.
1
u/Ok_Necessary_8923 Jan 29 '26 edited Jan 29 '26
I'd expect A is faster for small arrays for read operations, since the length and the data are contiguous in memory and will fit in a cache line and both are very likely used together in code.
Conversely, if you are modifying the array as you loop through it, perhaps B is faster for small arrays, as that should invalidate the cache line where the length is, leading to a miss and refetch.
1
u/BlindTreeFrog Jan 29 '26
Option B offends me for one reason.
why calculate it twice.. that's just two places to update if it changes.