Performance profiling basics in Ruby - Time & Space Complexity
Performance profiling helps us see how long parts of our code take to run.
We want to find which parts slow down as the input grows.
Analyze the time complexity of the following code snippet.
def sum_array(arr)
total = 0
arr.each do |num|
total += num
end
total
end
numbers = (1..1000).to_a
puts sum_array(numbers)
This code adds up all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items.
[X] Wrong: "Adding numbers is always fast and doesn't depend on input size."
[OK] Correct: Even simple steps take longer if there are more items to process.
Understanding how code time grows helps you explain your choices clearly and confidently.
"What if we used nested loops to add numbers in pairs? How would the time complexity change?"