How do I initialize an Array in swift with a specific capacity?
I\'ve tried:
var grid = Array ()
grid.reserveCapacity(16)
<
WARNING:
If you use the Array(repeating:count:)
initializer, you will encounter odd and unexpected behavior when using common array methods such as append(
which will immediately defeat the purpose of reserving capacity by adding the new value outside the created capacity instead of an earlier point in the array.
BETTER PRACTICE:
Swift arrays dynamically double to meet the storage needs of your array so you don't necessarily need to reserve capacity in most cases. However, there is a speed cost when you don't specify the size ahead of time as the system needs to find a new memory location with enough space and copy over each item one by one in O(N)
speed every time it doubles. On average, reallocation tends towards big O(LogN)
as the array size doubles.
If you reserve capacity you can bring the reallocation process down from O(N)
or O(NlogN)
on average down to nothing if you can accurately anticipate the size of the array ahead of time. Here is the documentation.
You can do so by calling reserveCapacity(:)
on arrays.
var myArray: [Double] = []
myArray.reserveCapacity(10000)