Does mutating a string in loop creates a new memory each time in swift?

For example,

var mutatingString = ""
for i in 0...5 {
mutatingString += String(i)
}

There's two things that can allocate memory here. The the String(i) part creates a new temporary string, and then += causes the mutable string to grow.

String(i) in this specific case will not allocate because the created string is shorter than string's inline storage (which I think is about 7 ASCII characters).

As for +=, it'll not allocate more memory every time. Each time its current allocated capacity is exhausted, it'll allocate enough memory to double its capacity, so as you append more it'll happen less and less often. You can avoid it however by calling mutatingString.reserveCapacity(predictedChararcterCount) beforehand, assuming you know how long your string will be.

To add, care should be taken when using this kind of function. Calling reserveCapacity too frequently can actually result in slower program overall.

1 Like

It’s even more. String stores strings with up to 15 UTF-8 bytes inline (on 64-bit platforms; it's up to 10 UTF-8 bytes on 32-bit).

Source: @Michael_Ilseman's blog post: UTF-8 String

Since Swift 5 switched to UTF-8, small strings now support up to 15 UTF-8 code units in length … Swift 5 supports small strings of up to 10 UTF-8 code units on 32-bit platforms.