Frozen objects in Ruby - Time & Space Complexity
When working with frozen objects in Ruby, it's important to understand how checking if an object is frozen affects performance.
We want to know how the time to check freezing grows as the program runs.
Analyze the time complexity of the following code snippet.
array = ["apple", "banana", "cherry"].map(&:freeze)
array.each do |item|
puts item.frozen?
end
This code freezes each string in an array and then checks if each item is frozen.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array to check if it is frozen.
- How many times: Once for each item in the array (n times).
Each item is checked once, so the total work grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work increases evenly as the list gets bigger.
Time Complexity: O(n)
This means the time to check frozen status grows in a straight line with the number of items.
[X] Wrong: "Checking if an object is frozen takes a long time because it inspects the whole object deeply."
[OK] Correct: Checking frozen status is a simple flag check and does not depend on object size.
Understanding how simple property checks scale helps you reason about performance in real code, making you confident in explaining your choices.
"What if we froze a nested array inside each item and checked frozen? How would the time complexity change?"