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

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

Leave a Comment

tech