Home
Blog
When to Use Arrays and Vectors in Rust
Updated
Dot Net Perls

When to Use Arrays and Vectors in Rust

In Rust we have two built-in ways to store multiple elements in order: arrays and vectors. Each type has its place, but most often we will want to use vectors. Arrays meanwhile can be used for performance optimizations and to reduce memory usage.

An array can store only a fixed number of elements—it cannot be resized. So it might have 10 i32 elements. Meanwhile a vector has a resizable buffer, so it can grow from 0 elements to millions of elements (with each push call).

Vectors tend to be easier to use, but arrays have some advantages:

Arrays use a fixed amount of memory and can be allocated on the stack, so the memory is guaranteed to be local and fast to access.
In my experience, arrays tend to perform better than vectors or strings when used as keys of a HashMap.
Since an array is guaranteed to contain a fixed number of elements, accessing a valid element index can be optimized by the compiler to have no bounds checks, further improving performance.

In places where performance is not critical, vectors are an easier and more convenient choice. They also lead to more resilient code in case more elements than expected are needed. But arrays have an important role in optimization, and can reduce memory usage.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen