In Rust, you can write (x * x) as x.powi(2).
Is there any reason for/against wrapping (x * x) (besides readability and personal preference) into a function/macro in Rust, or is this equivalent to using x.powi(2)?
(Where the constant 2in x.powi(2) is folded and converted into x * x)
No, with the current Rust compiler they are equivalent, generating exactly the same result.
You can check out the assembly code generated for both variants via the Rust Playground:
#![crate_type = "lib"]
pub fn square_mul(x:f64) -> f64 {
x*x
}
pub fn square_pow(x:f64) -> f64 {
x.powi(2)
}
Select a channel and release compilation mode, then press the ASM button in the top left corner. This is the output for Rust v1.10:
// square_mul:
mulsd %xmm0, %xmm0
retq
// square_pow:
mulsd %xmm0, %xmm0
retq
So Rust generates exactly the same code for both functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With