Swift 中的字符串连接是否生成新副本?
Does string concatenation in Swift make a new copy?
我可以像这样连接 Swift 中的两个字符串:
var c = "Hello World"
c += "!"
这会创建一个新的字符串吗? (分配一个新的内存块,复制原始字符串,连接“!”字符串并返回新内存。)或者,它是否就地更新原始字符串(如果原始块可以,则只分配一个新的内存块'适合角色)。
不,它不会制作新副本。如您所见,原始字符串有 changed.But 地址保持不变。
正如苹果文档中所说:https://developer.apple.com/documentation/swift/string
在性能优化部分:
"Although strings in Swift have value semantics, strings use a copy-on-write strategy to store their data in a buffer. This buffer can then be shared by different copies of a string. A string’s data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(n) time and space."
IOs 使用写时复制所以如果超过 1 个进程使用同一个变量,或者有超过 1 个副本(我不完全理解这部分),它会制作一个副本,但是如果该变量仅用于1个进程并且只有一个副本,那么您可以根据需要对其进行变异而不生成副本
我可以像这样连接 Swift 中的两个字符串:
var c = "Hello World"
c += "!"
这会创建一个新的字符串吗? (分配一个新的内存块,复制原始字符串,连接“!”字符串并返回新内存。)或者,它是否就地更新原始字符串(如果原始块可以,则只分配一个新的内存块'适合角色)。
不,它不会制作新副本。如您所见,原始字符串有 changed.But 地址保持不变。
正如苹果文档中所说:https://developer.apple.com/documentation/swift/string
在性能优化部分: "Although strings in Swift have value semantics, strings use a copy-on-write strategy to store their data in a buffer. This buffer can then be shared by different copies of a string. A string’s data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(n) time and space."
IOs 使用写时复制所以如果超过 1 个进程使用同一个变量,或者有超过 1 个副本(我不完全理解这部分),它会制作一个副本,但是如果该变量仅用于1个进程并且只有一个副本,那么您可以根据需要对其进行变异而不生成副本