Finlay Weber
Finlay Weber

Reputation: 4153

How are sized types useful in Rust?

This may sound like a question with an obvious answer, but please bear with me.

Why is it useful that the Rust compiler knows the size in memory a type takes at compile time?

Is this used for some optimization? if so what kinds?

Can one infer the size of the binary produced from the size of the types? That is, will a program using the i128 type produce a bigger binary compared to a program that uses u32? Or this "knowing of types" only affects the size of the memory the program will use at runtime?

Upvotes: 4

Views: 201

Answers (1)

Optimistic Peach
Optimistic Peach

Reputation: 4288

Knowing the size of the types in your program lets the compiler do a bunch of things:

  • Allocate the correct amount of memory for stack frames (since all your local variables are on the stack).
  • Allocate the correct amount of memory when heap-allocating a value.
  • Reason about things in the type system regarding sized-ness.

Additionally, this is beside any optimizations that the compiler can do, for example: size_of::<Option<Box<usize>>>() == size_of::<Box<usize>>(), since a null pointer is an invalid bit pattern for Box and can therefore be used to represent None.

This doesn't really affect the size of your binary in any meaningful way. Chances are that the biggest thing which affects that is actual code rather than data. Technically, different types often have different instructions, so yes, different types could result in differently sized binaries, however any difference because of that is probably overshadowed by other things (such as generic monomorphization of functions).

At runtime, the size of your data does matter however. For example, 4 million u8s have the size of 4mb, however 4 million u128s have the size of 64mb.

However, knowing the size of the types in your program is simply part of compilation -- it's not something that can be turned off and is something that the compiler could not function without knowing.

Upvotes: 4

Related Questions