An array's capacity—in particular, its reserveCapacity
method—lets you preallocate space in the array.
If you're adding elements to an array, and you exceed its capacity, then the array must increase its capacity. Since a Swift array stores its elements contiguously in memory, it must reallocate its internal storage and (usually) copy all of its elements from the old storage to the new storage. (Note that NSArray
isn't documented to store its elements contiguously, but we can deduce that Swift Array probably does based on the existence of the withUnsafeMutableBufferPointer
method.)
If you know in advance how many elements you intend to add to the array, you can use the reserveCapacity
method to preset the array's capacity so that it won't need to perform any reallocations (and associated copying).
The only reasons I can think of to ask an array for its capacity are to learn how the system works, and to debug a performance problem.
Usually you don't need to worry about reserving capacity. A reallocation is rarely a performance problem. Swift uses (I believe) an efficient reallocation schedule so that the number of reallocations is logarithmic in the final count of the array. E.g. if you add a million elements one at a time, Swift should perform no more than 20-30 reallocations.
But if you know your array will be very large (like, gigabytes on a Mac or tens of megabytes on an iOS device), or if you are filling the array in a performance-sensitive code path (e.g. filling an audio buffer that will start playing within microseconds), you may want to reserve capacity and avoid reallocations.
You should probably not worry about reserving capacity unless you know reallocations are a problem, either because the profiler shows that they're a bottleneck or because you have other evidence (like audio glitches in the audio buffer example).