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 aMove
struct with from
and to
fields, which are Square
. Square
is 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 u8
and 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?I have:
Best Answer:
Prou8
casting:- better cache utilization (objects are smaller); but might be only interesting when there are a lot of objects
Con
u8
:- 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 wrapperstd::ops::Index
:If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review