Deinitializers for cleanup in Swift - Time & Space Complexity
Deinitializers run when an object is about to be removed from memory. We want to understand how the time to clean up grows as more objects are created and destroyed.
How does the cleanup time change when many objects are deinitialized?
Analyze the time complexity of the following code snippet.
class FileHandler {
let fileName: String
init(name: String) {
fileName = name
print("Opening file \(fileName)")
}
deinit {
print("Closing file \(fileName)")
}
}
var handlers = [FileHandler]()
let n = 10 // or any other integer
for i in 1...n {
handlers.append(FileHandler(name: "file\(i).txt"))
}
handlers.removeAll()
This code creates n file handler objects, each opening a file, then removes all handlers triggering their cleanup.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and then deinitializing each FileHandler object.
- How many times: Exactly n times, once per object.
Each object requires a fixed amount of work to open and close its file. As n grows, the total work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 opens + 10 closes = 20 operations |
| 100 | About 100 opens + 100 closes = 200 operations |
| 1000 | About 1000 opens + 1000 closes = 2000 operations |
Pattern observation: The total work grows directly with the number of objects created and destroyed.
Time Complexity: O(n)
This means the cleanup time grows in a straight line as you create and remove more objects.
[X] Wrong: "Deinitializers run instantly no matter how many objects there are."
[OK] Correct: Each object needs its own cleanup work, so more objects mean more total cleanup time.
Understanding how cleanup scales helps you write efficient code that manages resources well, a skill valued in many programming tasks.
"What if the deinitializer also triggered cleanup of other objects? How would the time complexity change?"