Can you declare a variable to be saved in a CPU register in Rust?

Viewed 672

In C you can suggest to the compiler to keep a variable in a register like such:

int main() {
    register int varname = 1; 
    // ...
}

Is there an equivalent in Rust? Or can the compiler be trusted to do this by itself if an integer is used very frequently?

1 Answers

No, Rust does not have an equivalent

There isn't a way to hint to the compiler to use a register for a particular variable, just as there isn't in C++ at present.

Register is only a hint, and had only 1 certain effect in C

In C, register is only a hint to the compiler; the compiler still decides which variables get to be in a register.

What it does do, however, is prevent you from getting the address of the variable. The more important performance impact there is that it means that compiler can perform some optimisations which were otherwise unavailable, even when it doesn't actually put the value in a register.

And Rust gives you that already

Rust's ownership model permits you to have a single value which is never aliased, and which the compiler is free to optimise more heavily - there is no pointer assignment like C's (without using unsafe). The compiler is also free to use the ownership and lifetime information it has to inform its register usage.

Related