0

I read in Apple Docs:

"When you add elements to an array and that array begins to exceed its reserved capacity, the array allocates a larger region of memory and copies its elements into the new storage. The new storage is a multiple of the old storage’s size."

So, I opened the Playground and created some examples. The first example seems correct:

var array = [1, 2, 3, 4, 5]
array.capacity //5

array.append(contentsOf: [6, 7, 8, 9, 10])
array.capacity //10

array.append(11)
array.capacity //20

But I didn't understand the second example:

var array = [1, 2, 3, 4, 5]
array.capacity //5

array.append(contentsOf: [6, 7, 8, 9, 10, 11])
array.capacity //12

array.append(12)
array.capacity //12

Why is the capacity 12 in the second example? I didn't understand even reading the documentation and searching in Google.

Roberto Sampaio
  • 531
  • 1
  • 5
  • 15

1 Answers1

0

I recommend you to check Rob and Matt's answers here

Even though there's a reserveCapacity function, it's not advised

from the docs:

The Array type’s append(:) and append(contentsOf:) methods take care of this detail for you, but reserveCapacity(:) allocates only as much space as you tell it to (padded to a round value), and no more. This avoids over-allocation, but can result in insertion not having amortized constant-time performance.

casillas
  • 16,351
  • 19
  • 115
  • 215