0
0
Rubyprogramming~5 mins

String freezing for immutability in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String freezing for immutability
O(n)
Understanding Time Complexity

We want to understand how freezing a string affects the time it takes to run code that uses that string.

Specifically, does making a string unchangeable change how long operations take as the string gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


str = "hello world"
str.freeze

10.times do
  puts str
end
    

This code freezes a string to make it unchangeable, then prints it 10 times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Printing the string 10 times inside a loop.
  • How many times: 10 times, fixed number, not depending on string size.
How Execution Grows With Input

Printing the string depends on the string length, but the loop count is fixed at 10.

Input Size (n)Approx. Operations
10About 10 prints of 10 characters each
100About 10 prints of 100 characters each
1000About 10 prints of 1000 characters each

Pattern observation: The total work grows linearly with the string length, but the number of repeats is constant.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in direct proportion to the string length, regardless of freezing.

Common Mistake

[X] Wrong: "Freezing a string makes all operations on it instant or faster."

[OK] Correct: Freezing only stops changes; it does not speed up reading or printing the string, which still depends on string size.

Interview Connect

Understanding how immutability affects performance helps you write safer code without surprises about speed.

Self-Check

"What if we changed the loop to print the string n times instead of 10? How would the time complexity change?"