Fallback value computed eagerly instead of lazily
ID |
rust.performance.or_fun_call |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
Reports a call whose fallback argument is itself a function call - unwrap_or, or, ok_or, or_insert or get_or_insert - so the fallback is evaluated before the method runs, whether or not it is needed.
Rationale
Arguments are evaluated before the call, so the fallback runs on the success path too. Where it allocates, reads a file, formats a message or walks a collection, that cost is paid on every call for a value that is normally thrown away - and the fallback is exactly the branch the happy path is supposed to skip. Any side effect it has also happens unconditionally.
The following code illustrates the pattern detected by this rule:
use std::collections::HashMap;
fn expensive_default() -> u32 {
(1..1000).sum()
}
pub fn port(configured: Option<u32>) -> u32 {
// FLAGGED: Fallback value computed eagerly instead of lazily
configured.unwrap_or(expensive_default())
}