I've listened to Better Software conference, and once again heard people say "don't use Rust, it slows you down, you have to fight with it."
I guess part of it comes from the fact that in C you can both keep references to structures, and mutate them, which is impossible in Rust. I haven't done game development, and wonder where you need these references to mutated data?
In Rust, the obvious solution is, to use vector/array indices instead of refs. Accessing vector or array by index generates range check in assembly code, which may cost some cycles, and if your game needs to do this lots of times every frame, it becomes a problem.
I tried imagining a case where you'd really need lots of references, to access tightly connected data, and wouldn't want indices. I can think only of a game like Noita, where we simulate many particles, and have to access neighbor cells very often. I guess in this case, when the data doesn't move, and you process the cells in a single thread, why not store fixed references and skip the checks?
I wonder if working around this limitation is just a skill issue, or not.
So I thought of workarounds, and wanted to see how heavy or light they are. Here's a simple experimental code in Godbolt with 4 approaches:
- read data by reference
- get mutable access by
&mut my_vec[i] - same by
vec.get_mut(i).unwrap_or(|| MyError) - unsafe cast
usizeinto an immutable reference
Reading a reference takes 2 lines, #3 produces 5 lines of assembly code. To my surprize casting a reference produces almost 20 lines.
Some unknowns:
- Are the functions and the assembly code representative of what we'd get in the real code (where they're not isolated in separate functions)?
- I managed to cast to an immutable reference, but how to cast a mutable one?
- What's the C equivalent of reading or writing to an object by reference, stored in another object? How many lines of assembly does it generate, if any?
- What are other options? Let's assume the simplest case to begin with: we have fix-sized arrays, and they don't move, e.g. may even be
Pin.