0
0
Rubyprogramming~5 mins

Why hooks enable framework building in Ruby - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why hooks enable framework building
O(n)
Understanding Time Complexity

We want to understand how using hooks affects the speed of running code when building frameworks.

Specifically, how does the number of operations change as the program grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Framework
  def initialize
    @hooks = {}
  end

  def register_hook(name, &block)
    @hooks[name] ||= []
    @hooks[name] << block
  end

  def run_hook(name, *args)
    @hooks[name]&.each { |hook| hook.call(*args) }
  end
end
    

This code lets us add and run hooks by name, calling all functions registered for that hook.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over all hooks registered under a given name when running that hook.
  • How many times: Once for each hook function registered for that name.
How Execution Grows With Input

As we add more hooks for a name, running that hook calls more functions.

Input Size (number of hooks)Approx. Operations (hook calls)
1010
100100
10001000

Pattern observation: The number of operations grows directly with the number of hooks registered.

Final Time Complexity

Time Complexity: O(n)

This means running hooks takes time proportional to how many hooks are registered for that event.

Common Mistake

[X] Wrong: "Running hooks is always fast and constant time no matter how many hooks there are."

[OK] Correct: Each hook added means more functions to call, so running hooks takes longer as more are registered.

Interview Connect

Understanding how hooks scale helps you explain how frameworks stay flexible yet efficient as they grow.

Self-Check

What if we changed the code to run hooks in parallel instead of one by one? How would the time complexity change?