Result<> optimizations

Does Rust compiler optimize the following?

fn process(data: SomeDataType) -> Result<(), Error> {
    // a lot of processing and/or allocations here
    data.something()?;
    // a lot of processing and/or allocations here
    Ok(())
}

I mean is there any compiler optimization that checks the result of data.something() and return Err() in early stage instead of doing a lot of unnecessary work? Or do I have to write something like this to optimize that?

fn process(data: SomeDataType) -> Result<(), Error> {
    let something = data.something()?
    // a lot of processing and/or allocations here
    something;
    // a lot of processing and/or allocations here
    Ok(())
}

If you're asking whether there is an early return in your first example, the answer is yes i.e. the code represented by the second comment and the Ok(()) are not executed if data.something()? returns an Err(_) variant.

1 Like

It might reorder the early return before your other work if it can tell that your other work has no side-effects, but there are going to be many cases where it is unable to make the reordering because it can't tell that it doesn't have side-effects, or maybe the code does something that you don't consider to be a side-effect, but which the compiler does count. (e.g. increment, then decrement a ref-count)

2 Likes

Brilliant, thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.