Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit to use usize intsead of u8 when number will not exceed u8 range?

Tags:

types

rust

I was planning on using a tuple struct like struct Wrap(pub u8) to represent a number (which never exceeds 63) when it occurred to me that there may be no benefit to using u8 over usize instead, and using usize saves me from casting when I need to use the number to index into a slice. u8 "saves" me 3 bytes, but I'm not certain of that with data alignment on 64-bit processors.

Apart from "use the most appropriate data type", to which I think u8 and usize are equally applicable in my situation, what are the benefits to using u8 over usize and vice versa?


1 Answers

If your number is going to be used as an index, it should be a usize. That's essentially what usize means.

See also this question.

Sure, if you are going to have a bazillion of them, such that saving three bytes each actually matters, you might consider casting between u8 and usize. But you should think pretty hard about how much this might actually matter before you introduce this optimization with its extra complexity and potential footguns (or at least toestubs).

like image 85
d2718 Avatar answered Oct 24 '25 12:10

d2718