0
0
Rubyprogramming~5 mins

DSL building patterns in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: DSL building patterns
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated steps in the code.

  • Primary operation: Looping through all stored commands in run method.
  • How many times: Once for each command added to the DSL.
How Execution Grows With Input

As you add more commands, the run method calls each command's action one time.

Input Size (n)Approx. Operations
1010 calls to command actions
100100 calls to command actions
10001000 calls to command actions

Pattern observation: The number of operations grows directly with the number of commands added.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the DSL grows in a straight line as you add more commands.

Common Mistake

[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.

Interview Connect

Understanding how your DSL runs helps you write efficient code and explain your design choices clearly in interviews.

Self-Check

"What if the DSL stored commands in a nested structure and ran them recursively? How would the time complexity change?"