3

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?

  • from this [question](https://stackoverflow.com/questions/44685633/is-casting-between-integers-expensive), there is no need to worry about speed. Therefore it seems that, regarding your problem, the benefit of using `usize` would be the coding convenience, while the benefit of using `u8` would be the save of storage space (at the cost of coding convenience). – xc wang Oct 12 '22 at 03:44

1 Answers1

1

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

d2718
  • 175
  • 8