Pure functions concept in Ruby - Time & Space Complexity
We want to understand how the time a pure function takes changes as the input size grows.
How does the work inside a pure function scale when given bigger inputs?
Analyze the time complexity of the following code snippet.
def sum_array(arr)
arr.reduce(0) { |total, num| total + num }
end
numbers = [1, 2, 3, 4, 5]
result = sum_array(numbers)
This code defines a pure function that adds all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number in the array one by one.
- How many times: Once for each element in the array.
As the array gets bigger, the function adds more numbers, so it takes more steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Pure functions always run instantly no matter the input size."
[OK] Correct: Even pure functions do work on each input item, so bigger inputs take more time.
Understanding how pure functions scale helps you write clear and predictable code that performs well as data grows.
"What if we changed the function to call itself recursively for each element? How would the time complexity change?"