Swift array.capacity vs array.count

后端 未结 3 983
我在风中等你
我在风中等你 2020-12-10 06:39

I understand the array.count ( the number of elements in the array ). count is useful to iterate over the array\'s elements. I sort of get the gist of array.capacit

3条回答
  •  温柔的废话
    2020-12-10 06:51

    The total number of elements that the array can contain without

    allocating new storage.

    Every array reserves a specific amount of memory to hold its contents. 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. This exponential growth strategy means that appending an element happens in constant time, averaging the performance of many append operations. Append operations that trigger reallocation have a performance cost, but they occur less and less often as the array grows larger.

    The following example creates an array of integers from an array literal, then appends the elements of another collection. Before appending, the array allocates new storage that is large enough store the resulting elements.

    var numbers = [10, 20, 30, 40, 50]
    
    numbers.count == 5
    
    numbers.capacity == 5
    
    numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
    
    numbers.count == 10
    
    numbers.capacity == 12
    

提交回复
热议问题