0
0
Rubyprogramming~5 mins

Proc creation and call in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Proc creation and call
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of Procs grows, the work grows too.

Input Size (n)Approx. Operations
10About 20 (10 creations + 10 calls)
100About 200 (100 creations + 100 calls)
1000About 2000 (1000 creations + 1000 calls)

Pattern observation: The total work grows directly with the number of Procs created and called.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of Procs, the total time roughly doubles too.

Common Mistake

[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.

Interview Connect

Understanding how repeated creation and calls affect time helps you reason about code efficiency and resource use in real projects.

Self-Check

"What if we created one Proc and called it multiple times instead of creating many Procs? How would the time complexity change?"