0
0
Rubyprogramming~5 mins

Why functional patterns complement OOP in Ruby - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why functional patterns complement OOP
O(n)
Understanding Time Complexity

We want to see how combining functional patterns with object-oriented programming affects how long code takes to run.

Specifically, we ask: How does adding functional style change the work done as input grows?

Scenario Under Consideration

Analyze the time complexity of the following Ruby code mixing OOP and functional style.


class Calculator
  def initialize(numbers)
    @numbers = numbers
  end

  def sum_squares
    @numbers.map { |n| n * n }.reduce(0, :+)
  end
end

calc = Calculator.new([1, 2, 3, 4])
puts calc.sum_squares
    

This code defines a class holding numbers and uses functional methods to square and sum them.

Identify Repeating Operations

Look for loops or repeated work inside the code.

  • Primary operation: The map method loops over each number to square it.
  • Secondary operation: The reduce method loops again to add all squared numbers.
  • How many times: Each method loops once over all numbers, so two passes total.
How Execution Grows With Input

As the list of numbers grows, the code does more work in two passes.

Input Size (n)Approx. Operations
10About 20 (10 for map + 10 for reduce)
100About 200 (100 + 100)
1000About 2000 (1000 + 1000)

Pattern observation: The work grows roughly twice as fast as the input size because of two passes.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly in proportion to how many numbers we have.

Common Mistake

[X] Wrong: "Using two loops means the time complexity is squared, like O(n²)."

[OK] Correct: The loops run one after another, not inside each other, so their times add up, not multiply.

Interview Connect

Understanding how functional methods work inside classes helps you explain clear, readable code that scales well.

Self-Check

What if we combined the map and reduce into a single loop? How would the time complexity change?