DSL building patterns in Ruby - Time & Space Complexity
When creating a DSL (Domain Specific Language) in Ruby, we want to know how the time it takes to run grows as we add more commands or rules.
We ask: How does the execution time change when the DSL script gets longer or more complex?
Analyze the time complexity of the following Ruby DSL builder code.
class SimpleDSL
def initialize
@commands = []
end
def command(name, &block)
@commands << {name: name, action: block}
end
def run
@commands.each { |cmd| cmd[:action].call }
end
end
# Usage
# dsl = SimpleDSL.new
# dsl.command(:say_hello) { puts 'Hello' }
# dsl.command(:say_goodbye) { puts 'Goodbye' }
# dsl.run
This code collects commands in a list and runs each command's action one by one.
Look for loops or repeated steps in the code.
- Primary operation: Looping through all stored commands in
runmethod. - How many times: Once for each command added to the DSL.
As you add more commands, the run method calls each command's action one time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to command actions |
| 100 | 100 calls to command actions |
| 1000 | 1000 calls to command actions |
Pattern observation: The number of operations grows directly with the number of commands added.
Time Complexity: O(n)
This means the time to run the DSL grows in a straight line as you add more commands.
[X] Wrong: "Adding more commands won't affect run time much because each command is simple."
[OK] Correct: Even if each command is simple, running all commands means doing more work overall, so time grows with the number of commands.
Understanding how your DSL runs helps you write efficient code and explain your design choices clearly in interviews.
"What if the DSL stored commands in a nested structure and ran them recursively? How would the time complexity change?"