Reclaiming reserved space from an Array (and other containers)

I know that when appending items to an array that the underlying allocation of additional storage is based on the existing size. i.e from Array.swift in stdlib:

  /// Because arrays increase their allocated capacity using an exponential
  /// strategy, appending a single element to an array is an O(1) operation
  /// when averaged over many calls to the `append(_:)` method.

In the situation where I don't know in advance how big an array is going to get and hence can't use reserveCapacity, it likely that by the time I've finished creating the array that there could be a whole load of reserved space that will never be used. And for arrays with tens of thousands of items, that could be a substantial amount of wasted memory.

Is there a guaranteed way to shrink the array's storage back to its minimum required size once I know its not going to be modified further?


Terms of Service

Privacy Policy

Cookie Policy