0
0
Rubyprogramming~5 mins

Immutable data with freeze in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Immutable data with freeze
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the array gets bigger, the program prints more numbers, so it does more work.

Input Size (n)Approx. Operations
1010 print operations
100100 print operations
10001000 print operations

Pattern observation: The work grows directly with the number of items. Freezing does not add extra repeated work.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced each with a nested loop over the array? How would the time complexity change?"