0
0
Rubyprogramming~5 mins

Performance profiling basics in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Performance profiling basics
O(n)
Understanding Time Complexity

Performance profiling helps us see how long parts of our code take to run.

We want to find which parts slow down as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def sum_array(arr)
  total = 0
  arr.each do |num|
    total += num
  end
  total
end

numbers = (1..1000).to_a
puts sum_array(numbers)

This code adds up all numbers in an array and returns the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every element in the array.
How Execution Grows With Input

As the array gets bigger, the time to add all numbers grows in a straight line.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: Doubling the input doubles the work needed.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items.

Common Mistake

[X] Wrong: "Adding numbers is always fast and doesn't depend on input size."

[OK] Correct: Even simple steps take longer if there are more items to process.

Interview Connect

Understanding how code time grows helps you explain your choices clearly and confidently.

Self-Check

"What if we used nested loops to add numbers in pairs? How would the time complexity change?"