Class.new for dynamic class creation in Ruby - Time & Space Complexity
When we create classes dynamically using Class.new, it is important to understand how the time to create these classes grows as we create more of them.
We want to know how the time needed changes when we make many classes this way.
Analyze the time complexity of the following code snippet.
classes = []
10.times do
klass = Class.new do
def greet
"Hello"
end
end
classes << klass
end
This code creates 10 new classes dynamically, each with a simple method, and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new class with
Class.newinside a loop. - How many times: The loop runs 10 times, so the class creation happens 10 times.
Each time we add one more class creation, the total time increases by roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 class creations |
| 100 | 100 class creations |
| 1000 | 1000 class creations |
Pattern observation: The time grows steadily and directly with the number of classes created.
Time Complexity: O(n)
This means if you create twice as many classes, it will take about twice as long.
[X] Wrong: "Creating classes dynamically is instant and does not depend on how many we make."
[OK] Correct: Each class creation takes some time, so making more classes adds up and takes longer overall.
Understanding how dynamic class creation scales helps you reason about code that builds things on the fly, a useful skill in many programming tasks.
"What if we added methods inside the class dynamically for each class? How would the time complexity change?"