0
0
Rubyprogramming~5 mins

Frozen objects in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Frozen objects
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

Each item is checked once, so the total work grows directly with the number of items.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work increases evenly as the list gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the time to check frozen status grows in a straight line with the number of items.

Common Mistake

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

Interview Connect

Understanding how simple property checks scale helps you reason about performance in real code, making you confident in explaining your choices.

Self-Check

"What if we froze a nested array inside each item and checked frozen? How would the time complexity change?"