0
0
Rustprogramming~5 mins

Why Rust is used - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why Rust is used
O(n)
Understanding Time Complexity

We want to understand how Rust's features affect the speed of programs.

How does Rust help programs run efficiently as they get bigger?

Scenario Under Consideration

Analyze the time complexity of a simple Rust function that sums numbers in a vector.


fn sum_numbers(numbers: &Vec<i32>) -> i32 {
    let mut total = 0;
    for &num in numbers.iter() {
        total += num;
    }
    total
}
    

This code adds up all numbers in a list and returns the total.

Identify Repeating Operations

Look for loops or repeated steps.

  • Primary operation: Adding each number to total inside a loop.
  • How many times: Once for every number in the list.
How Execution Grows With Input

As the list gets bigger, the time to add all numbers grows too.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Rust always makes code run instantly, no matter the input size."

[OK] Correct: Rust helps write fast code, but if your code loops over many items, it still takes longer as the input grows.

Interview Connect

Knowing how Rust handles loops and data helps you explain why your code runs fast and scales well.

Self-Check

"What if we used recursion instead of a loop to sum numbers? How would the time complexity change?"