Reputation: 2996
My project has grown and so have my extensions with utility methods to access certain types. I have an extension for UINib
for example that looks like this:
extension UINib {
static let collectionViewCellNib1: UINib = UINib(nibName: "collectionViewCellNib1", bundle: Bundle.main)
static let collectionViewCellNib2: UINib = UINib(nibName: "collectionViewCellNib2", bundle: Bundle.main)
static let collectionViewCellNib3: UINib = UINib(nibName: "collectionViewCellNib3", bundle: Bundle.main)
// etc.
}
Now in regard of memory consumption: If I understood it correctly, the moment I access any one of those type properties, it is not garbage collected. It will stay in the memory as long as my application exists/isn't terminated.
Would my application benefit in regard of memory consumption if I would refactor the code above to:
extension UINib {
static var collectionViewCellNib1: UINib {
return UINib(nibName: "collectionViewCellNib1", bundle: Bundle.main)
}
static var collectionViewCellNib2: UINib {
return UINib(nibName: "collectionViewCellNib2", bundle: Bundle.main)
}
static var collectionViewCellNib3: UINib {
return UINib(nibName: "collectionViewCellNib3", bundle: Bundle.main)
}
// etc.
}
Since my UINib
instances are now bound to a view, which has a life cycle of it's own, all objects connected to this life cycle will be released, when the view is destroyed/removed.
Why should I choose constant type properties over computed type properties, if the latter is better for memory consumption?
Upvotes: 4
Views: 883
Reputation: 86651
The second example with the computed properties will (probably) give you a new UINib every time you get the property. It is correct that the memory for each one will be reclaimed when you have finished with them, but that might be offset by having multiple UINib objects representing the same NIB on the go at once.
The other issue is that constructing a UINib is an expensive operation in terms of CPU cycles and IO (you have to read a file on disk and create objects from what is in it). That may more than offset the advantage of a smaller memory footprint.
Upvotes: 2