Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is better removeAll of Array or initialising the Array again?

Tags:

swift

Initializing array again is better than removeAll() of array? What will be the effect on Heap memory in both cases?

like image 268
Ravindra Kumar Sonkar Avatar asked Jan 27 '26 01:01

Ravindra Kumar Sonkar


1 Answers

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.

like image 195
Rob Napier Avatar answered Jan 29 '26 18:01

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!