Why Rust is used - Performance Analysis
We want to understand how Rust's features affect the speed of programs.
How does Rust help programs run efficiently as they get bigger?
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.
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.
As the list gets bigger, the time to add all numbers grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[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.
Knowing how Rust handles loops and data helps you explain why your code runs fast and scales well.
"What if we used recursion instead of a loop to sum numbers? How would the time complexity change?"