Instance_variable_get and set in Ruby - Time & Space Complexity
We want to understand how fast Ruby's instance_variable_get and instance_variable_set methods run as the number of instance variables grows.
Specifically, how does the time to get or set a variable change when there are more variables in an object?
Analyze the time complexity of the following code snippet.
class Person
def initialize
@name = "Alice"
@age = 30
end
def get_name
instance_variable_get(:@name)
end
def set_name(new_name)
instance_variable_set(:@name, new_name)
end
end
person = Person.new
person.get_name
person.set_name("Bob")
This code creates a Person object with two instance variables and uses instance_variable_get and instance_variable_set to read and update the @name variable.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Hash lookup in the object's instance variable table to find the value matching the given name.
- How many times: The lookup happens once per call, with constant-time average case regardless of the number of variables.
As the number of instance variables grows, the time to access the right one remains roughly constant due to hash table properties.
| Input Size (number of instance variables) | Approx. Operations |
|---|---|
| 10 | About 1-2 hash probes |
| 100 | About 1-2 hash probes |
| 1000 | About 1-2 hash probes |
Pattern observation: The time stays constant as the number of instance variables increases (average case O(1) for hash lookups).
Time Complexity: O(1)
This means the time to get or set an instance variable is constant on average, thanks to hash table storage in Ruby objects.
[X] Wrong: "Getting or setting an instance variable requires scanning through all variables linearly."
[OK] Correct: Ruby stores instance variables in a hash table (st_table), enabling average O(1) lookups by symbol ID, not linear search.
Understanding how instance variable access scales helps you write efficient Ruby code and shows you know how Ruby handles objects internally.
"What if Ruby stored instance variables in an array instead of a hash? How would that change the time complexity?"