Why metaprogramming is powerful in Ruby - Performance Analysis
We want to see how metaprogramming affects how long Ruby code takes to run.
Specifically, how does creating methods or code on the fly change the work done as input grows?
Analyze the time complexity of the following Ruby metaprogramming example.
class Person
[:name, :age, :email].each do |attr|
define_method(attr) do
@attributes[attr]
end
end
def initialize(attributes)
@attributes = attributes
end
end
This code dynamically creates getter methods for each attribute in a list.
Look for loops or repeated actions that affect performance.
- Primary operation: Looping over the attribute list to define methods once.
- How many times: Exactly once per attribute during class definition, not per object.
As the number of attributes grows, the setup work grows too, but only once.
| Input Size (attributes) | Approx. Operations |
|---|---|
| 3 | 3 method definitions |
| 10 | 10 method definitions |
| 100 | 100 method definitions |
Pattern observation: The work grows linearly with the number of attributes, but only once when the class loads.
Time Complexity: O(n)
This means the setup time grows in a straight line with the number of attributes, but it happens just once, not every time you use the class.
[X] Wrong: "Metaprogramming makes the program slower every time it runs because it creates methods repeatedly."
[OK] Correct: The method creation happens once when the class is loaded, not every time you create an object or call a method.
Understanding how metaprogramming affects time helps you explain why Ruby code can be both flexible and efficient.
What if we defined methods inside the initialize method instead of at class load? How would the time complexity change?