0
0
Rubyprogramming~5 mins

Lambda creation and behavior in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda creation and behavior
O(n)
Understanding Time Complexity

We want to understand how creating and using lambdas affects the time it takes for a program to run.

Specifically, we ask: how does the number of operations grow when we create and call lambdas?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


my_lambda = ->(n) { n * 2 }

10.times do |i|
  puts my_lambda.call(i)
end
    

This code creates a lambda that doubles a number, then calls it 10 times, printing each result.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the lambda inside a loop.
  • How many times: The lambda is called once for each iteration of the loop (10 times here).
How Execution Grows With Input

Each time we increase the number of calls, the total work grows in a straight line.

Input Size (n)Approx. Operations
1010 calls to lambda
100100 calls to lambda
10001000 calls to lambda

Pattern observation: The total work grows directly with the number of times the lambda is called.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as we call the lambda more times.

Common Mistake

[X] Wrong: "Creating a lambda inside the loop is free and does not add to time."

[OK] Correct: Creating a lambda inside a loop means making a new function each time, which adds work and slows the program.

Interview Connect

Understanding how lambdas behave helps you explain how your code runs and scales, a skill that shows you think about efficiency clearly.

Self-Check

"What if we created the lambda inside the loop instead of before it? How would the time complexity change?"