replacingOccurrences(of:,with:) always returns new string?

Do string functions such as "replacingOccurrences" and "trimmingCharacters" always return a new string, even if the old string did not need to be modified?

In other words -- if I'm doing a large number of "replacingOccurrences" in my app but only a small number of the strings actually contain the sequence I want to replace, should I check to see if the sequence exists before calling replacingOccurrences, in order to avoid an unnecessary string allocation?

I would guess that Swift would return the same string if it didn't require any modifications, but the documentation just says "Returns a new string".

Thanks, Frank

If I understand correctly, Swift does copy-on-write, so returning a new string that is equal to the old string is just an increment of the reference counter.

replacingOccurrences(of:,with:) always returns new string?
 
 
Q