Using if as expression in Rust - Time & Space Complexity
We want to see how the time it takes to run code changes when using if as an expression in Rust.
Specifically, we ask: does using if this way affect how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
fn max_value(a: i32, b: i32) -> i32 {
let max = if a > b { a } else { b };
max
}
fn main() {
let result = max_value(10, 20);
println!("Max is {}", result);
}
This code uses if as an expression to choose the larger of two numbers and returns it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison between two numbers.
- How many times: Exactly once per function call.
Since the code only compares two numbers once, the work stays the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 comparison |
| 100 | 1 comparison |
| 1000 | 1 comparison |
Pattern observation: The number of operations does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the time to run this code stays the same no matter how big the input numbers are.
[X] Wrong: "Using if as an expression makes the code slower because it does more work."
[OK] Correct: The if expression only does one comparison and picks a value immediately, so it does not add extra work as input grows.
Understanding how simple expressions like if work helps you explain your code clearly and shows you know how to write efficient, clean Rust code.
"What if we changed the code to compare elements in a list using if inside a loop? How would the time complexity change?"