I was thinking about minimizing the size of enum
s containing Vec
s, and it just occurred to me: what's the disadvantage of storing the size and capacity fields of the standard library's Vec
in the heap-allocated part? Specifically, Vec
could be defined as (ignoring NonNull
for simplicity):
struct Vec<T> {
ptr: *const (),
PhantomData<T>,
}
with the ptr
being allocated with
- an alignment of
max(align_of<usize>(), align_of<T>())
, and - an initial padding that is
max(2*size_of<usize>(), align_of<T>())
bytes to be used to storesize
andcap
.
Then, Vec
would be the same size as Box
. This would reduce the struct size of Vec
and String
3x and allow them to be passed as a single register.
The slight disadvantages that come to mind are:
- The pointer would always require an alignment of at least
align_of<usize>()
. -
len()
would require a branch:if self.is_empty() { // self.ptr == 0x1 0 } else { unsafe { ptr::read(self.ptr as *const usize) } }
Given that this is not how Vec
s are typically implemented in system languages, is there some major disadvantage that alludes me?