Performance of Rust vector (`Vec<T>`) versus array (`[T; n]`)

Viewed 13778

How much am I losing in terms of performance when using a vector versus an array in Rust?

By performance I mean: speed of element access or speed of iteration.

1 Answers

They both store data in a linear contiguous array where accessing or iterating is both an O(1) operation so there's no difference in performance. The only case when vector is slower is probably for some small lists because array is stored on stack in the current stack frame, hence their data is highly probably already loaded to the CPU cache. Vector OTOH stores data on the heap so data will not be available in cache before they're first accessed

Vector also has one more level of redirection because you need to load the address of the array first so the first memory access may also be slower, but that's just negligible

The other time when vector is much worse is when you use a vector of vector vs a multidimensional array because each vector is allocated separately and lies all around memory which is not good for caching. See Access time of vec vs array

See also Difference between array vs. vec for memory and cpu usage

Related