Why class-level behavior matters in Ruby - Performance Analysis
When we look at class-level behavior in Ruby, we want to see how the time it takes to run code changes as we use more objects or call more class methods.
We ask: How does the work grow when we use class methods compared to instance methods?
Analyze the time complexity of the following Ruby class with class-level and instance-level methods.
class Counter
@@count = 0
def self.increment
@@count += 1
end
def increment_instance
@count ||= 0
@count += 1
end
end
10.times { Counter.increment }
c = Counter.new
100.times { c.increment_instance }
This code shows a class method increasing a shared count and an instance method increasing a count for one object.
Look at the loops and method calls that repeat work.
- Primary operation: Incrementing a number inside loops.
- How many times: Class method increments 10 times; instance method increments 100 times.
As the number of increments grows, the time grows directly with how many times we call the methods.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The time grows in a straight line as we increase the number of increments.
Time Complexity: O(n)
This means the time to run grows directly with the number of times we call the increment methods.
[X] Wrong: "Class-level methods always run faster because they share data."
[OK] Correct: Both class and instance methods take time proportional to how many times they run, so sharing data doesn't make the time smaller by itself.
Understanding how class-level and instance-level methods scale helps you explain how your code handles more data or users, a skill that shows you think about efficiency clearly.
"What if the class method called the instance method inside its loop? How would the time complexity change?"