Comparing structs vs classes decision in Swift - Performance Comparison
When choosing between structs and classes in Swift, it's important to understand how their operations grow as your data size increases.
We want to see how the time cost changes when working with many instances of each type.
Analyze the time complexity of creating and copying structs versus classes.
struct PointStruct {
var x: Int
var y: Int
}
class PointClass {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
// Creating and copying 1000 instances
var structPoints = [PointStruct]()
var classPoints = [PointClass]()
for i in 0..<1000 {
structPoints.append(PointStruct(x: i, y: i))
classPoints.append(PointClass(x: i, y: i))
}
// Copying struct array
let copiedStructPoints = structPoints
// Copying class array
let copiedClassPoints = classPoints
This code creates arrays of structs and classes, then copies the arrays to compare how copying behaves.
Look for loops and copying actions that repeat work.
- Primary operation: Loop creating 1000 instances of structs and classes.
- How many times: 1000 times for creation; copying arrays happens once but behaves differently.
Creating instances grows linearly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations |
| 100 | 100 creations |
| 1000 | 1000 creations |
Copying struct arrays duplicates all data, so operations grow with n. Copying class arrays only copies references, so it stays almost constant.
Time Complexity: O(n)
This means the time to create or copy grows directly with the number of items.
[X] Wrong: "Copying a class array duplicates all objects like structs."
[OK] Correct: Copying a class array only copies references, not the objects themselves, so it is much faster than copying structs.
Understanding how structs and classes behave with copying helps you explain performance choices clearly and confidently in real projects.
What if we changed the struct to contain a large array? How would copying the struct array affect time complexity?