user1002430
user1002430

Reputation:

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

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?

Upvotes: 4

Views: 1060

Answers (1)

d2718
d2718

Reputation: 365

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).

Upvotes: 3

Related Questions