Proc creation and call in Ruby - Time & Space Complexity
We want to understand how the time it takes to create and call a Proc changes as we do it more times.
How does the number of Proc creations and calls affect the total work done?
Analyze the time complexity of the following code snippet.
procs = []
10.times do |i|
procs << Proc.new { i * 2 }
end
procs.each do |p|
p.call
end
This code creates 10 Procs that double a number, then calls each Proc once.
Look at what repeats in the code.
- Primary operation: Creating Procs inside a loop and calling each Proc.
- How many times: Each happens 10 times, once per item.
As the number of Procs grows, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 creations + 10 calls) |
| 100 | About 200 (100 creations + 100 calls) |
| 1000 | About 2000 (1000 creations + 1000 calls) |
Pattern observation: The total work grows directly with the number of Procs created and called.
Time Complexity: O(n)
This means if you double the number of Procs, the total time roughly doubles too.
[X] Wrong: "Creating a Proc once means calling it many times is free or very fast."
[OK] Correct: Each call still takes time, so calling many times adds up and affects total time.
Understanding how repeated creation and calls affect time helps you reason about code efficiency and resource use in real projects.
"What if we created one Proc and called it multiple times instead of creating many Procs? How would the time complexity change?"