Why classes exist alongside structs in Swift - Performance Analysis
When we look at why Swift has both classes and structs, it helps to think about how their performance changes as we use them more.
We want to understand how the cost of using classes or structs grows when we work with many objects.
Analyze the time complexity of creating and copying structs versus classes.
struct Point {
var x: Int
var y: Int
}
class Circle {
var center: Point
var radius: Int
init(center: Point, radius: Int) {
self.center = center
self.radius = radius
}
}
// Creating many instances
var points = [Point]()
var circles = [Circle]()
for i in 0..
This code creates many Point structs and Circle class instances, showing how they behave when copied or referenced.
Look at what repeats as we create many objects.
- Primary operation: Creating and storing each Point struct and Circle class instance.
- How many times: Exactly n times, once per loop iteration.
As n grows, the number of creations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations of structs and classes |
| 100 | 100 creations of structs and classes |
| 1000 | 1000 creations of structs and classes |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and store these objects grows in a straight line with the number of items.
[X] Wrong: "Classes and structs always have the same performance because they both hold data."
[OK] Correct: Structs copy all their data when assigned or passed, which can be costly for large data, while classes use references, so copying is cheaper but managing references adds overhead.
Understanding why Swift has both classes and structs helps you explain design choices clearly and shows you know how performance can change with different data types.
"What if we changed the struct Point to have many properties or nested structs? How would the time complexity of copying change?"