Identity operators (=== and !==) in Swift - Time & Space 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.
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 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.
As the list gets bigger, the number of checks grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 identity checks |
| 100 | 100 identity checks |
| 1000 | 1000 identity checks |
Pattern observation: The number of checks grows directly with the number of people.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets longer.
[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.
Understanding how identity checks scale helps you explain how your code handles object comparisons efficiently.
"What if we used a dictionary to find the target instead of a loop? How would the time complexity change?"