1

I just measured account size with std::mem::size_of because I was curious how space is calculated for vectors. Following the docs, I would have assumed that size_of would add 4 bytes for each vector, independently of the data type. But it adds 24 bytes instead, independently of the type.

size_of for all of the following three structures results in 24 bytes:

#[account]
#[derive(Default)]
pub struct Testing {
    data: Vec<u8>,   
}
#[account]
#[derive(Default)]
pub struct Testing {
    data: Vec<Pubkey>,   
}
#[account]
#[derive(Default)]
pub struct Testing {
    data: String,   
}

What am I missing here? Why is it always 24 bytes for dynamic data types when the docs say it should be 4 bytes?

2 Answers 2

2

In Rust, Vec is implemented as a fat pointer with three values: a pointer to a heap-allocated buffer (8 bytes), a usize for the number of elements in the vector (8 bytes on a 64-bit machine), and a usize for the capacity of the buffer (8 bytes, again). (src: Rust Docs) So when you call mem::size_of, that's why you're getting 24 bytes as a result.

But when Borsh serializes the vector to be stored in an account, none of that stuff matters. It only cares about the items actually stored by the vector. So Borsh is actually serializing a slice of the vector, as shown here. And when Borsh encodes slices as a combination of a u32 representing their length (this is where the 4 bytes in the Anchor docs comes from) and each element in the slice sequentially. (src)

1

All vectors take up 24 bytes on the stack regardless of how many elements they have. The data stored in each are on the heap, not on the stack.

2
  • thanks for explaining. So the documentation is kind of misleading. Commented Aug 23, 2022 at 6:54
  • The size of Vec is 24 bytes from compiler's layout point of view. However, on Solana,, its layout is different, and hence on that platform, it's size is 4 + (number of elements) * (size of element on the solana). Commented Jun 9, 2023 at 21:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.