10

Are variables of type Vec<[f3; 5]> stored as one contiguous array (of Vec::len() * 5 * sizeof(f32) bytes) or is it stored as a Vec of pointers?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user72961
  • 143
  • 1
  • 6

1 Answers1

12

The contents of a Vec<T> is, regardless of T, a single heap allocation, of self.capacity() * std::mem::size_of::<T>() bytes. (Vec overallocates—that’s the whole point of Vec<T> instead of Box<[T]>—so it’s the capacity, not the length, that matter in this calculation.) The actual Vec<T> itself takes three words (24 bytes on a 64-bit machine).

[f32; 5] is just a chunk of memory containing five 32-bit floating-point numbers, with no indirection; this comes to twenty bytes (hence std::mem::size_of::<[f32; 5]>() == 20).

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • 1
    Thanks. But `Vec>` would be stored as a `Vec` of pointers right? – user72961 Jul 13 '15 at 01:31
  • 6
    A `Vec>` would have a series of tightly packed 3-word structs. One of those words would be a pointer. The other two are the capacity and length. – Shepmaster Jul 13 '15 at 03:04
  • What about alignment? How big is the heap for `Vec`, `Vec` (is it equal to capacity), `Vec<(u8, u8)>`, `Vec<[u8; 3]>`? – ArtemGr Jul 13 '15 at 07:42
  • 1
    @ArtemGr: what I said is precise. – Chris Morgan Jul 13 '15 at 10:40
  • 1
    @ChrisMorgan Precise, but not reduntant. For the point to properly come across it have to be enlarged with examples and rehashings, sometimes. So, no alignment for the members I take it? (p.s. example of a similar explanation for C++: http://stackoverflow.com/a/13284631/257568). Still, the structs seem to be padded (http://is.gd/YbS3Nj) so sometimes the members of a `Vec` will appear to be aligned. – ArtemGr Jul 13 '15 at 12:08
  • @ChrisMorgan Why `Vec` cares about http://doc.rust-lang.org/std/mem/fn.min_align_of.html there http://doc.rust-lang.org/std/vec/struct.Vec.html#method.map_in_place? – ArtemGr Jul 13 '15 at 15:16