Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance difference between a squared function and directly calling powi(2) in Rust?

Tags:

rust

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)

like image 777
ideasman42 Avatar asked Nov 15 '25 02:11

ideasman42


1 Answers

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.

like image 77
aSpex Avatar answered Nov 17 '25 19:11

aSpex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!