Lambda creation and behavior in Ruby - Time & Space 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?
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 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).
Each time we increase the number of calls, the total work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to lambda |
| 100 | 100 calls to lambda |
| 1000 | 1000 calls to lambda |
Pattern observation: The total work grows directly with the number of times the lambda is called.
Time Complexity: O(n)
This means the time to run grows in a straight line as we call the lambda more times.
[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.
Understanding how lambdas behave helps you explain how your code runs and scales, a skill that shows you think about efficiency clearly.
"What if we created the lambda inside the loop instead of before it? How would the time complexity change?"