Instance Property インスタンスプロパティ

capacity

The total number of elements that the array can contain without allocating new storage. その配列が新しいストレージを割り当てることなく含むことができる要素の総数。

Declaration 宣言

var capacity: Int { get }

Discussion 解説

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 == 10

See Also 参照

Inspecting an Array 配列を調査する