Adding to a collection like this (unless String is the collection itself, you essentially add its characters representation with this code) is linear, not quadratic. A line in Swift has an internal buffer, the size of which doubles each time it is filled, which means that you will see fewer and fewer redistributions as you add. The documentation describes the addition in this way as an โamortizedโ operation O (1): most of the time O (1) is added, but sometimes it needs to reallocate the row storage.
Arrays, sets, and dictionaries have the same behavior, although you can also reserve a specific capacity for the array (using reserveCapacity(_:) ) if you know that you will add many times.
All of these collections use copy-on-write to guarantee the semantics of the value. Here x and y share a buffer:
let x = "a" let y = x
If you mutate x , it gets a new unique copy of the buffer:
x += "b" // x == "ab" // y == "a"
After that, x has its own buffer, so subsequent mutations will not require a copy.
x += "c" // no copy unless buffer is full
source share