#vector #stack #small #buffer #optimization


fixed-capacity vector allocated on the stack

7 releases (4 breaking)

0.5.0 Jan 22, 2022
0.4.0 Dec 31, 2021
0.3.0 Dec 28, 2021
0.2.1 Sep 5, 2021
0.1.1 Aug 28, 2021

#936 in Data structures

47 downloads per month
Used in 3 crates

MIT license

632 lines


A fixed-capacity vector whose elements are stored locally. In particular, they can be allocated on the stack.

License: MIT Build Status

LocalVec is a fixed-capacity vector, i.e., its size or length increases and decreases as elements are pushed into and popped from the vector, respectively. However, its capacity always remains the same and must be determined at compile time.

The elements of a LocalVec are stored on a local buffer inside the LocalVec itself, not on a remote buffer allocated on the heap.

LocalVec vs Vec

LocalVec's elements reside locally, i.e., inside it:

use local_vec::LocalVec;
let mut vec = LocalVec::<_, 4>::new();

vec contents in the code above are:

That is, vec has a local buffer, and the i32 values 3 and 7 are stored inside vec itself, not in a remotely-allocated buffer on the heap.

In contrast, Vec allocates a remote buffer on the heap and contains a pointer to that buffer instead of the buffer itself:

let mut v = Vec::with_capacity(4);
v.extend([3, 7]);

That is, v points to a remote buffer, and the i32 values 3 and 7 are stored on that remote buffer, which is allocated on the heap.

Compile-time capacity

Since the size of a LocalValue depends on its capacity, the capacity of a LocalVec must be determined at compile time. This is achieved with a constant generic argument thanks to const generics:

let mut vec = LocalVec::<i32, 4>::new();
    const generic argument <--|

Allocating on the Stack or the Heap

Technically, the elements LocalVec contains are stored locally in the LocalVec. Whether or not these elements are on the stack depends on whether the LocalVec itself is allocated on the stack. For example:

let vec = Box::new(LocalVec::<u8, 32>::new());

vec is allocated on the heap, and so are the elements it contains because they are stored inside vec itself. There isn't an additional heap allocation as it would have been the case with Vec, though.

No runtime deps