0
0
Rustprogramming~5 mins

Generic functions in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic functions
O(n)
Understanding Time Complexity

We want to see how the time a generic function takes changes as the input size grows.

How does using a generic type affect the speed when the function runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn print_items(items: &[T]) {
    for item in items {
        println!("{}", item);
    }
}

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    print_items(&numbers);
}
    

This function prints each item in a list, using a generic type that can be any printable value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list.
  • How many times: Once for every item in the input slice.
How Execution Grows With Input

As the list gets bigger, the function prints more items, so it takes longer.

Input Size (n)Approx. Operations
1010 print actions
100100 print actions
10001000 print actions

Pattern observation: The time grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items to print.

Common Mistake

[X] Wrong: "Using generics makes the function slower because it has to handle many types."

[OK] Correct: The generic function runs the same loop regardless of type; the time depends on input size, not the type itself.

Interview Connect

Understanding how generic functions behave helps you explain code efficiency clearly and confidently in real projects and interviews.

Self-Check

"What if we changed the function to print pairs of items instead of single items? How would the time complexity change?"