Why generics provide type safety in Swift - Performance Analysis
We want to see how using generics affects the speed of code as input grows.
Specifically, we ask: How does type safety with generics impact the number of steps the program takes?
Analyze the time complexity of the following generic function.
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
This function searches for a value in an array of any type that can be compared for equality.
Look for loops or repeated checks.
- Primary operation: Looping through each item in the array to compare values.
- How many times: Up to once per item, until the value is found or the array ends.
As the array gets bigger, the function may check more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The number of comparisons grows directly with the number of items.
Time Complexity: O(n)
This means the time to find the value grows in a straight line with the array size.
[X] Wrong: "Generics make the search faster because they check types at compile time."
[OK] Correct: Generics ensure type safety but do not speed up the search itself, which still depends on the number of items.
Understanding how generics keep code safe without slowing it down shows you can write flexible and reliable programs.
"What if the array was sorted and we used a binary search instead? How would the time complexity change?"