Default method implementations in Rust - Time & Space Complexity
We want to understand how the time it takes to run code with default method implementations changes as the input grows.
Specifically, how does calling a default method affect the total work done when used in a loop?
Analyze the time complexity of the following code snippet.
trait Greeter {
fn greet(&self) {
println!("Hello!");
}
}
struct Person;
impl Greeter for Person {}
fn greet_many(times: usize) {
let p = Person;
for _ in 0..times {
p.greet();
}
}
This code defines a trait with a default greet method and calls it many times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the default greet method inside a loop.
- How many times: The greet method is called once for each loop iteration, so
timestimes.
Each time we increase the input times, the greet method runs that many times.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The total work grows directly with the number of times we call the method.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of method calls.
[X] Wrong: "Since the method is default and simple, calling it many times is almost free and does not add up."
[OK] Correct: Even simple methods take time each call, so calling them repeatedly adds up linearly with the number of calls.
Understanding how default methods behave in loops helps you explain performance clearly and shows you can reason about code efficiency beyond just syntax.
"What if the greet method called another method inside that also loops over the input? How would the time complexity change?"