0
0
Rustprogramming~5 mins

Default method implementations in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default method implementations
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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 times times.
How Execution Grows With Input

Each time we increase the input times, the greet method runs that many times.

Input Size (times)Approx. Operations
1010 greet calls
100100 greet calls
10001000 greet calls

Pattern observation: The total work grows directly with the number of times we call the method.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of method calls.

Common Mistake

[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.

Interview Connect

Understanding how default methods behave in loops helps you explain performance clearly and shows you can reason about code efficiency beyond just syntax.

Self-Check

"What if the greet method called another method inside that also loops over the input? How would the time complexity change?"