Identity comparison (===) in Swift - Time & Space Complexity
We want to understand how fast identity comparison works in Swift.
Specifically, how the cost changes when we compare objects using the identity operator ===.
Analyze the time complexity of the following code snippet.
class Person {}
let people = [Person(), Person(), Person(), Person(), Person()]
for i in 0..
This code checks each person in the array to see if it is the same object as the first person.
Look for repeated actions that take time.
- Primary operation: The identity comparison
===inside the loop. - How many times: It runs once for each person in the array.
As the number of people grows, the number of comparisons grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The number of comparisons grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Identity comparison === is instant and does not depend on the number of items."
[OK] Correct: While each comparison is quick, doing many comparisons adds up, so total time depends on how many times you compare.
Understanding how identity checks scale helps you explain performance when working with object references in Swift.
What if we stopped the loop early when we find the first match? How would the time complexity change?