How Ruby interprets code at runtime - Performance & Efficiency
When Ruby runs code, it reads and executes instructions step by step. We want to see how the time it takes grows as the code gets bigger or more complex.
How does Ruby's way of reading code affect how long the program takes to run?
Analyze the time complexity of the following Ruby code snippet.
def sum_array(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
n = 10 # or any integer value
arr = (1..n).to_a
sum_array(arr)
This code adds up all numbers in an array from 1 to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the array, so n times.
As the array gets bigger, Ruby has to add more numbers, so the work grows with the size.
| 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; double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input.
[X] Wrong: "Ruby reads all code instantly, so the size of the input doesn't affect time."
[OK] Correct: Ruby reads and runs each instruction one by one, so more data means more steps and more time.
Understanding how Ruby runs code step by step helps you explain how your programs behave as they grow. This skill shows you know what happens behind the scenes.
"What if we changed the array to a nested array and summed all numbers inside? How would the time complexity change?"