4

Array in swift can grow dynamically according to the size, but it does not seem to be shrinking.

var x: [Int] = []
for i in 0...1000 {
    x.append(i)
}
for i in reverse(1000...0) {
    x.removeAtIndex(0)
}

The capacity of x remains large. I also tried removeLast() and copy it to a new variable, but does not seem to reduce the capacity.

3
  • Is there a particular reason you want to shrink the array's capacity? Commented Jan 19, 2015 at 8:04
  • @SebastianDressler would leaving an unnecessarily large capacity waste memory consumption? Commented Jan 19, 2015 at 8:05
  • Technically yes, but I think (although not entierly sure about the implementation details), there is some logic behind that behaviour. E.g. if you decide to re-resize it again, the system does not have to allocate memory again. On the other hand, at some specific size, it may shrink the capacity. Commented Jan 19, 2015 at 8:08

2 Answers 2

4

To reset the capacity, use .removeAll(keepCapacity: false):

var x: [Int] = []
for i in 0...1000 {
    x.append(i)
}

x.capacity // -> 1,532
x.removeAll(keepCapacity: false)
x.capacity // -> 0

If you want to keep the elements after optimizing the capacity, copy it with Array() constructor:

for i in 0...1000 {
    x.append(i)
}
for i in reverse(0...999) {
    x.removeAtIndex(0)
}
x.capacity // -> 1532
x = Array(x) // -> [1000]
x.capacity // -> 2
Sign up to request clarification or add additional context in comments.

Comments

0

The growing/shrinking of the memory allocated by an array is part of the memory management of the runtime. Memory allocation might benefit from not directly de-allocating memory when the number of elements stored in the array is reduced. E.g., it may happen, that after elements were removed, new elements are added to the array. In that case, new memory would need to be allocated.

Also distinct between count and capacity.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.