Immutable data with freeze in Ruby - Time & Space Complexity
We want to see how using freeze to make data unchangeable affects how long a program takes to run.
Specifically, we ask: does freezing data change the work done when we use it?
Analyze the time complexity of the following code snippet.
array = [1, 2, 3, 4, 5]
array.freeze
array.each do |num|
puts num
end
This code freezes an array to make it unchangeable, then prints each number in it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array with
each. - How many times: Once for each element in the array (n times).
As the array gets bigger, the program prints more numbers, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with the number of items. Freezing does not add extra repeated work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the array, even when it is frozen.
[X] Wrong: "Freezing the array makes the program slower because it adds extra work every time we use the array."
[OK] Correct: Freezing only happens once and does not repeat during the loop. Using the frozen array is just as fast as using a normal array.
Understanding how immutable data affects performance helps you write safer code without surprises about speed. It shows you can think about both correctness and efficiency together.
"What if we replaced each with a nested loop over the array? How would the time complexity change?"