In this post, we will see how to resolve In Rust, is it faster to store larger types or to store smaller ones and cast them all the time?
Question:I’m developing a chess engine in Rust. I have a
tofields, which are
Squareis a struct containing a
usize, so that I can use it directly when accessing board elements of the position. Since in Rust indexing must be done with
usize, I’m wondering what’s the fastest way to handle this situation (note that move generation should be as fast as possible). I understand it’s more memory friendly to store
u8and cast them every time I need to use them as an index, but is it faster? What would be the idiomatic way to approach this?
- better cache utilization (objects are smaller); but might be only interesting when there are a lot of objects
- casting might require additional instructions on some platforms; but these are usually only register operations which are optimized by the cpu
Idiomatic way to avoid the
as usize: implement a wrapper
If you have better answer, please add a comment about this, thank you!