vec_vs_array.txt (2408B)
1 =============================================================================== 2 ARRAY vs VEC 3 =============================================================================== 4 5 +-----------------+-------------------------------+-------------------------------+ 6 | Feature | Array `[T; N]` | Vector `Vec<T>` | 7 +-----------------+-------------------------------+-------------------------------+ 8 | Size | Fixed at compile time | Dynamic at runtime | 9 | Memory Location | Usually stack | Heap (pointer on stack) | 10 | Flexibility | Static (cannot push/pop) | Dynamic (can grow/shrink) | 11 | Metadata Size | 0 bytes (known at compile | 24 bytes (pointer, length, | 12 | | time) | capacity) | 13 +-----------------+-------------------------------+-------------------------------+ 14 15 An array in Rust is a fixed-size collection of elements that all share the same 16 data type. The size of an array must be known at compile time, meaning it cannot 17 grow or shrink during program execution. 18 19 Arrays vs Vectors in Rust 20 21 While both arrays ([T; N]) and vectors (Vec<T>) store elements of the same type 22 in contiguous memory, their primary differences lie in memory management and 23 flexibility. Arrays are typically stored entirely on the stack, which makes them 24 incredibly fast to allocate but inflexible. In contrast, a vector stores its 25 actual elements on the heap, while keeping a small control structure on the 26 stack consisting of a pointer to the heap data, the current length, and the 27 total capacity. This allows vectors to dynamically resize at runtime using 28 methods like .push(), which arrays cannot do. 29 30 Performance Implications 31 32 Because arrays live on the stack and have no metadata, accessing their elements 33 is direct and avoids the pointer indirection required by a vector's heap 34 allocation. However, this stack allocation means that when you move an array, 35 you must copy every single element within it. Moving a vector is generally much 36 cheaper because it only requires copying the metadata pointer, length, and 37 capacity (usually 24 bytes), rather than the potentially massive underlying 38 data. Therefore, arrays are highly efficient for small, fixed-size data sets, 39 whereas vectors are better suited for large collections or data that changes 40 size over time.