<ao> | Adetunji's Blog

Vector allocates memory

It has a size but if the size is exceeded it doesn't give an error but it doubles the initial memory size and then reallocates the data to the new memory size.

The capacity() will print out the memory size of a vector.

let mut my_vec: Vec<i8> = vec!(2);
println!("{}", my_vec.capacity());  //prints 1

my_vec.push(8);
println!("{}", my_vec.capacity());  //prints 4

The vector at this point has one reallocation.

We can make it more efficient by giving it a capacity of 4 from the start using the associated function with_capacity() to build the vector.

let mut my_vec: Vec<i8> = Vec::with_capacity(4);

my_vec.push(1)
println!("{}", my_vec.capacity());  //prints 4

my_vec.push(8);
println!("{}", my_vec.capacity());  //prints 4

#note #rust