0
0
Swiftprogramming~5 mins

Identity comparison (===) in Swift - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the number of people grows, the number of comparisons grows the same way.

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

Pattern observation: The number of comparisons grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how identity checks scale helps you explain performance when working with object references in Swift.

Self-Check

What if we stopped the loop early when we find the first match? How would the time complexity change?