Attr_reader, attr_writer, attr_accessor in Ruby - Time & Space Complexity
Let's see how using attr_reader, attr_writer, and attr_accessor affects the speed of our Ruby code.
We want to know how the time to access or change object properties grows as we use these shortcuts.
Analyze the time complexity of the following Ruby class using these attribute helpers.
class Person
attr_accessor :name
attr_reader :age
attr_writer :email
def initialize(name, age, email)
@name = name
@age = age
@email = email
end
end
person = Person.new("Alice", 30, "alice@example.com")
person.name = "Bob"
puts person.age
person.email = "bob@example.com"
This code defines a class with automatic getter and setter methods for its properties.
Look for operations that happen multiple times or grow with input.
- Primary operation: Accessing or setting instance variables via generated methods.
- How many times: Each access or set is a single direct operation, no loops or recursion.
Each time you get or set a property, it takes the same small amount of time, no matter how many properties or objects you have.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple property accesses or sets |
| 100 | 100 simple property accesses or sets |
| 1000 | 1000 simple property accesses or sets |
Pattern observation: The time grows directly with how many times you access or set properties, but each is quick and does not depend on other factors.
Time Complexity: O(1)
This means each property access or change takes the same small amount of time, no matter how many objects or properties exist.
[X] Wrong: "Using attr_accessor makes property access slower because it adds extra code."
[OK] Correct: These helpers just create simple methods that run very fast, so they do not slow down your program noticeably.
Understanding how these shortcuts work and their speed helps you write clean and efficient Ruby code, a skill useful in many coding situations.
"What if we replaced attr_accessor with manual getter and setter methods? How would the time complexity change?"