Initializing array again is better than removeAll() of array? What will be the effect on Heap memory in both cases?
These are literally the same thing as long as you don't reserve capacity.
Here is the empty initializer for Array:
public init() {
_buffer = _Buffer()
}
Here is removeAll:
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
}
else {
self.replaceSubrange(indices, with: EmptyCollection())
}
}
In both cases, it just creates a new _Buffer (which is either _ArrayBuffer or _ContiguousArrayBuffer), and assigns it to _buffer. There is no difference in memory usage or other behavior. _buffer is the only property of Array so there is no memory difference between an Array and its buffer (Swift structs have no extra headers). removeAll() is implemented as creating a new Array.
If you plan to refill the array to a similar size, then keepCapacity: true may prevent some reallocations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With