Class instance variables as alternative in Ruby - Time & Space Complexity
We want to understand how using class instance variables affects the time it takes to run code.
Specifically, how does the program's work grow when we access or change these variables?
Analyze the time complexity of the following code snippet.
class Counter
@count = 0
def self.increment
@count += 1
end
def self.count
@count
end
end
100.times { Counter.increment }
puts Counter.count
This code uses a class instance variable @count to keep track of a number that increases each time increment is called.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
incrementmethod updates the class instance variable. - How many times: It runs 100 times in a loop.
Each call to increment does a simple addition and assignment.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions and assignments |
| 100 | 100 additions and assignments |
| 1000 | 1000 additions and assignments |
Pattern observation: The work grows directly with the number of times increment is called.
Time Complexity: O(n)
This means the time to run grows in a straight line as we increase how many times we update the class variable.
[X] Wrong: "Accessing a class instance variable is slow and grows with the number of instances."
[OK] Correct: Class instance variables belong to the class itself, not instances, so accessing or updating them takes the same time regardless of how many objects exist.
Understanding how class instance variables work and their time cost helps you explain design choices clearly and shows you know how Ruby handles data at the class level.
What if we changed the class instance variable to a class variable (@@count)? How would the time complexity change?