0
0
Swiftprogramming~5 mins

Identity operators (=== and !==) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Identity operators (=== and !==)
O(n)
Understanding Time Complexity

Let's see how checking if two objects are the same affects how long a program takes to run.

We want to know how the time to compare objects grows as we do more comparisons.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {}

let people = [Person(), Person(), Person(), Person(), Person()]
let target = people[2]

for person in people {
    if person === target {
        print("Found the target person")
    }
}
    

This code checks each person in a list to see if it is the exact same object as the target.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop goes through each person in the array.
  • How many times: Once for every person in the list.
How Execution Grows With Input

As the list gets bigger, the number of checks grows in the same way.

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

Pattern observation: The number of checks grows directly with the number of people.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets longer.

Common Mistake

[X] Wrong: "Checking if two objects are the same is instant and does not depend on list size."

[OK] Correct: While each check is quick, doing many checks adds up as the list grows.

Interview Connect

Understanding how identity checks scale helps you explain how your code handles object comparisons efficiently.

Self-Check

"What if we used a dictionary to find the target instead of a loop? How would the time complexity change?"