0
0
Rustprogramming~5 mins

Why variables are needed in Rust - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why variables are needed
O(n)
Understanding Time Complexity

We want to understand how using variables affects the steps a program takes.

How does storing and reusing values change the work done as the program runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn sum_first_n(n: u32) -> u32 {
    let mut sum = 0;
    for i in 1..=n {
        sum += i;
    }
    sum
}

This code adds numbers from 1 to n using a variable to keep the running total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that adds each number to the sum variable.
  • How many times: The loop runs n times, once for each number from 1 to n.
How Execution Grows With Input

Explain the growth pattern intuitively.

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

Pattern observation: The number of steps grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input number gets bigger.

Common Mistake

[X] Wrong: "Using a variable makes the program run faster or slower by itself."

[OK] Correct: Variables just hold values; the time depends on how many times we use them, not on having them.

Interview Connect

Understanding how variables affect steps helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if we replaced the for-loop with a formula that calculates the sum directly? How would the time complexity change?"