I've noticed that arrays are not declared with specific sizes in swift. I know c++ where this is not the case and to use a dynamic list I need to use a vector object. Is there a certain vector object in swift or do arrays adjust size at runtime?
-
Did you have a look at https://developer.apple.com/documentation/swift/array or https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html ? – Martin R Jun 26 '17 at 05:15
-
No I did not, I'll check though. Thanks. Should have though of that – Joseph Jun 26 '17 at 05:16
-
See this page https://developer.apple.com/documentation/accelerate/working_with_vectors – Peter Schorn May 10 '20 at 05:34
1 Answers
Is there a certain vector object in swift or do arrays adjust size at runtime?
The latter: Any array reserves a well-determined amount of memory to hold its elements. Whenever you append elements to an array, making the array exceed the reserved capacity, it allocates a larger region of memory, whose size is a multiple of the old storage's capacity.
Why does an array grow its memory exponentially?
Exponential growth is meant to average the time performance of the append()
(add element(s)) function. Whenever the memory is increased, the elements are copied into the new storage. Of course, when memory reallocation is triggered, the performance of the append()
function is significantly reduced, though this happens less often as the array becomes bigger and bigger.
I suggest you to look over the Array Documentation, especially the "Growing the Size of an Array" Chapter. If you want to preallocate space in the array, it is good to know of the reserveCapacity(_:)
method. Related SO post for more details about capacity
.

- 1
- 1

- 4,719
- 5
- 26
- 44