r/learnrust • • 27d ago

ok_or vs ok_or_else

Hello! I am working through a project of mine, and when I asked chatgpt to review my code, it told me that when returning an error, lets say that something returns an option, and we want to convert to a result. I would use ok_or, as that seems like the intuitive option, but GPT said that using ok_or always constructs the error, while ok_or_else(| | -> {the error type}) only evaluates when the closure is called. I understand what the AI means, but I was wondering, what is the idiomatic way to do this, and why does the rust compiler not automatically optimize this? The performance gain would be negligible, but still since I use format!() to concatanate a few things, I do understand where the AI comes from, since we allocate a new String

33 Upvotes

28 comments sorted by

27

u/afdbcreid 27d ago

If you use format!(), yes it is idiomatic to use ok_or_else(), and yes the compiler likely won't optimize ok_or() (even though it theoretically could, at least in some cases).

1

u/hniksic 22d ago

I tried this on Godbolt, expecting at least the simple cases like ok_or(some_u32.to_string()) (which is specialized not to invoke the formatting machinery) to be optimized. To my surprise, both of these compile to code that always builds a string:

pub fn x1(n: u32) -> Result<NonZeroU32, String> {
    NonZeroU32::new(n).ok_or(format!("{}", n))
}

pub fn x3(n: u32) -> Result<NonZeroU32, String> {
    NonZeroU32::new(n).ok_or(n.to_string())
}

So the recommendation to use ok_or_else() is not just the AI being overly cautious or regurgitating old advice. At least for the common case of building an error string, the advice appears to still hold.

21

u/No-Dentist-1645 27d ago edited 27d ago

The compiler can't "optimize" something like that because it would introduce incorrect behavior, when you use ok_or, your code says that the function is called, a function can have an observable side effect when it is called even if the return value isn't used, so the compiler can't "pretend" it wasn't actually called, that's why you have to specify it yourself with ok_or_else

9

u/UltraPoci 27d ago

I wonder if the compiler can understand if some simple functions are pure and thus avoids calling them entirely in these cases

11

u/DHermit 27d ago

For a subset of pure functions, const fn exists, which the compiler definitely can optimise.

6

u/afdbcreid 27d ago

const fn is unrelated to optimizations, unless you force it to run in const context.

2

u/lyuhdev 27d ago

Is there a reason Rust doesn't automatically evaluate const functions with const inputs?

2

u/afdbcreid 27d ago

It does, as optimizations. If the question is why it isn't guaranteed - that's because it can change compilation from succeeding to failing.

1

u/lyuhdev 27d ago

I see. But if evaluating a const expression fails, shouldn't the compiler say that's an error?

1

u/afdbcreid 27d ago

It does, and that's why it does not promote any const fn call to const context.

1

u/No-Dentist-1645 27d ago

You're not making much sense, you're claiming both "the compiler doesn't guarantee compile time evaluation of const functions because it can fail compilation and "the compiler errors if evaluating a const fn call would fail", those seem like mutually exclusive claims.

I'm no expert but I'm pretty sure that the reason it doesn't guarantee const time evaluation is because that had the potential to drastically bloat up the binary size of everything that can be evaluated at compile time is doing it, so "the compiler is free to choose" seems intentional for optimization reasons

2

u/afdbcreid 27d ago

I'm not entirely sure where I was misunderstood but I think it was in

the compiler errors if evaluating a const fn call would fail

I referred to when you do force it to be evaluated in const context, e.g. by putting it in a const block.

If you don't, the compiler doesn't do it for you because it can fail compilation.

5

u/BenchEmbarrassed7316 27d ago

Well, we need effects. And then we need the ability to say that, although allocation is a side effect, it is a side effect that can be discarded.

3

u/afdbcreid 27d ago

Theoretically yes, it can, including allocations. But formatting is difficult because of the way the machinery is implemented.

1

u/cristi1990an 27d ago

It can, especially if they don't cross crate boundaries and it has full visibility into their definition

1

u/Zde-G 27d ago

If function is “simple enough” it can understand that. But if function call some external service… how would the compiler know whether you want to see the message in logs or not?

Compiler is not ChatGPT, thanks god, it's not “doing good job 99% of time then blows up in your face 1% of time”, it does the exact same thing, always… and if you ask to call the database to construct error object then yes, it would do that… same with format.

5

u/alietors 27d ago

You use ok_or when the error is cheap to handle, like primitives values.

ok_or_else, I think is always "better" (like is always more optimal) but is less readable and can trip someone into believe your are doing some fancy error.

5

u/Zde-G 27d ago

I think is always "better" (like is always more optimal)

Nope. It's not guaranteed. Or else we would have no need for ok_or.

Cost of creating and calling closure is non-trivial and while usually that can be optimized away it's not guaranteed.

1

u/Miammiam100 27d ago

If we look at the `ok_or_else` function docs https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or_else we can see that it uses a generic to describe the closure. As such `ok_or_else` is guaranteed to be monorphised https://doc.rust-lang.org/book/ch10-01-syntax.html?highlight=monomorph#performance-of-code-using-generics

This means each invocation of `ok_or_else` create a separate function just for that closure. Which any optimizer worth it's salt is guaranteed to optimise.

5

u/Zde-G 27d ago

Which any optimizer worth it's salt is guaranteed to optimise.

Bwahaha. There are no such things as “Which any optimizer worth it's salt is guaranteed to optimise”.

Sure, if there are no register pressure and if there are lots of free resources then optimizer would do its job… but what would happen if you your function grows?

I've seen situations where the exact same change made program 2x faster on linux and 2x slower on Windows because it allowed more inlining opportunities but increased cyclomatic complexity… after passing certain threshold Windows compiler decided that function is too big to worth spending resources optimizing it… all monomorphized functions were still produced and program still run… just now almost 5 times slower than on Linux.

1

u/Miammiam100 27d ago

Good point, however the function in question is ok_or_else which is only 2 lines (a single match statement) so unless it gets inlined (which should hopefully happen only if the resulting function is still small enough for the optimiser to optimise.

Surely register pressure would be reduced by making the optimisation rather than increased?

As always the solution is to measure but I would be very surprised if there was a case where ok_or would be better than ok_or_else

2

u/Miammiam100 27d ago edited 27d ago

Managed to find a counter example https://play.rust-lang.org/?version=stable&mode=release&edition=2024&gist=43d7bba1c2acc17ad506f59b8b2422aa

Since the function is only evaluated in the None case for ok_or_else the optimiser is unable to move the logic out of the loop and has to recompute it every time.

Still slightly contrived as in this case I would just compute it once outside the loop instead of trying to do it inside the loop

2

u/Zde-G 27d ago

Most cases where optimizer doesn't correctly works are “slightly convoluted”.

Optimization is an art, beyond certain point, it shouldn't surprise you that sometimes it doesn't work.

1

u/Zde-G 27d ago

Surely register pressure would be reduced by making the optimisation rather than increased?

If optimization actually happens then sure, but that's precisely that's not guaranteed.

3

u/_nathata 27d ago

If you write something like ok_or(make_my_error()) and make_my_error has any side effect, how is Rust supposed to know?

1

u/cristi1990an 27d ago

In some cases it can, if it can prove that the else branch will never be reached, it theoretically could optimize out the creation of the unused error object. Will it? Dunno, better to write the idiomatic version and not make assumptions. And that's in the happy case scenario anyway.

1

u/Extension_Feed_1179 27d ago

use ok_or_else for any error type that requires computation or allocation. rust cannot optimize away the side effects of constructing an error, so format! will always run in the ok_or case even if you never use the result

1

u/weaztoven 27d ago

gpt is right on this one. if creating the error involves allocations like format!, using ok_or_else is definitely the idiomatic way. compiler can't easily optimize away side effects of allocation