Constants in classes in Ruby - Time & Space Complexity
Let's see how accessing constants inside classes affects the time it takes for a program to run.
We want to know how the time changes when we get constant values from classes.
Analyze the time complexity of the following code snippet.
class MyClass
CONST_VALUE = 42
def get_constant
CONST_VALUE
end
end
obj = MyClass.new
10.times { obj.get_constant }
This code defines a class with a constant and a method that returns it. Then it calls that method multiple times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the method that returns the constant.
- How many times: The method is called 10 times in a loop.
Getting a constant value from a class is very fast and does not depend on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple constant lookups |
| 100 | 100 simple constant lookups |
| 1000 | 1000 simple constant lookups |
Pattern observation: The time grows directly with the number of times you ask for the constant, but each lookup is very quick and does not get slower with bigger input.
Time Complexity: O(n)
This means the total time grows linearly with how many times you access the constant, but each access is very fast and simple.
[X] Wrong: "Accessing a constant inside a class takes constant time no matter how many times you do it, so the loop doesn't add time."
[OK] Correct: Each access is fast, but if you do it many times, the total time adds up linearly with the number of accesses.
Understanding how constants behave in classes helps you explain how simple data access works in real programs, a useful skill for many coding tasks.
"What if the constant was a large array and the method returned a copy each time? How would the time complexity change?"