Should I choose the minimum integer size as much as possible?

While there are many integer types in Rust such as i32 and u8, I am not sure which type should I choose in terms of writing performant code. For example, which code is better in performance, A or B?

// A
let x: u8 = 1;
let must_be_i32: i32 = x as i32 + 1;
// B
let x: i32 = 1;
let must_be_i32: i32 = x + 1;

I am always writing like A to use less memory but writing type conversion so many times is tedious and feeling what am I doing is meaningless…

So my question is when to use singned/unsigned and i8/i6…i128 types.

  • 4

    “which code is better in performance?” – this is a poor example since the optimizer would const-eval this away. But anyway, x as i32 is a no-op as far as a modern CPU is concerned (just a different load instruction). If you’re interested in performance, a smaller integer size may reduce memory pressure and improve cache friendliness, but won’t really improve numerical speed (unless your operations can be vectorized). And I only say “may” because alignment and padding around your reduced integers may prove the point moot.

    – 

  • 3

    If your thinking is “1 is smaller than 256, so my variable should be u8 to reduce memory usage” you should probably stop doing that. Especially if we’re only talking about local variables.

    – 




  • “Premature optimization” – textbook example of it.

    – 




I also struggled with having to choose between integral types when I started with Rust. In C/C++ there is a clear default, which is int. In Rust I recommend (and I think this is the community consensus) to use i32 as the default, unless there is a good reason to use something else.

Leave a Comment