Why hooks enable framework building in Ruby - Performance Analysis
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?
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 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.
As we add more hooks for a name, running that hook calls more functions.
| Input Size (number of hooks) | Approx. Operations (hook calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the number of hooks registered.
Time Complexity: O(n)
This means running hooks takes time proportional to how many hooks are registered for that event.
[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.
Understanding how hooks scale helps you explain how frameworks stay flexible yet efficient as they grow.
What if we changed the code to run hooks in parallel instead of one by one? How would the time complexity change?