Does a Mutable variable cause more overhead than an Immutable Variable?

Arrays are generally faster than Vectors, because they are not mutable, and because they don't need to allocate more memory. Is the same true for Variables?

Would:

let mut x: i32 = 1;

be slower than:

let x: i32 = 1;

Does the compiler remove the unnecessary muts in the code?

mut on local variables has no impact on code generation whatsoever. It is only used by the compiler to prevent some programs from compiling.

4 Likes

Arrays are actually mutable. It is only the length that cannot be modified.

4 Likes

You can test such things on rust.godbolt.org, but remember to always add -O to the flags field on there! Otherwise godbolt gives useless noisy result.

In Rust variables don't even exist when the program runs, so how they're declared means very little. The optimizer will figure out how the data is used, and optimize for specific usage.

Also in Rust all exclusively owned values are always mutable. mut is just a weak lint for humans, but it's meaningless and irrelevant for the compiled code. Note that this is different from &mut which is strongly enforced and does affect optimizations in some cases.

3 Likes

As @alice mentioned, array elements are mutable, but not array lengths. Really, there's three fundamental owned sequence types w.r.t. mutability:

  • [T; N]: elements can be mutated, but length is set at compile time.
  • Box<[T]>: elements can be mutated, but length is set on creation and cannot be modified. (This is similar to a T[] in C# or Java.)
  • Vec<T>: elements can be mutated, and length can be modified at any time (but only when no references to the elements are active).