Instance variables (@) in Ruby - Time & Space Complexity
Let's see how using instance variables affects the time it takes for a program to run.
We want to know if accessing or setting instance variables changes how long the program takes as it runs.
Analyze the time complexity of the following code snippet.
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
person = Person.new("Alice")
puts person.greet
This code creates a person with a name stored in an instance variable and then greets using that name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the instance variable
@nameinside thegreetmethod. - How many times: Each time
greetis called, the instance variable is accessed once.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 accesses to @name if greet called 10 times |
| 100 | 100 accesses to @name if greet called 100 times |
| 1000 | 1000 accesses to @name if greet called 1000 times |
Pattern observation: The time grows directly with how many times you call the method that uses the instance variable.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times you call the method that accesses the instance variable.
[X] Wrong: "Accessing an instance variable is slow and adds extra loops behind the scenes."
[OK] Correct: Accessing an instance variable is a simple, direct operation that takes the same time each time, not a loop or repeated search.
Understanding how instance variables work helps you explain how your code stores and accesses data efficiently, a key skill in programming.
"What if we changed the instance variable to a class variable? How would the time complexity change when accessing it multiple times?"