what are the advantages of using smaller integer types in rust?

Viewed 98

I am learning rust and in the official tutorial, the author assigned the value 5 to a variable like so:

let x: i32 = 5;

I thought this was weird as one could use u8 as the type and the program would run fine. This got me thinking, are there any advantages to using a lower bit number? Is it faster?

1 Answers

The main advantage is that they use less memory. A vector<i32> with 1 billion elements will use 4GB, while a vector<u8> will use 1GB. This can be a significant advantage regardless of speed.

Arithmetic on smaller integer types on modern CPUs is not faster in general. There are some issues with using only part of a register but optimizers will almost certainly resolve these performance problems for you.

When you have a lot of integers and the optimizer can make use of vectorization (for example adding your 1 billion integers in the vector) then smaller types will typically yield better performance, because more of them fit in a SIMD register.

If you use them just as one scalar stack variable like in your example, I highly doubt there will be a difference in 99% of cases. Here other considerations are more important:

  • A bigger type will make overflows less likely, maybe you did calculate your maximal possible value wrong.

  • For public interfaces bigger types are more future proof.

  • Its better to cast from i8 to i32 than the other way round.

Related