當我使用+ =運算符將一個字符串追加到Swift中的另一個字符串時,代碼中執行了哪個進程?如果我做了str1 + = str2,在str1的末尾分配了內存,並且在那裏複製了str2,或者是爲新字符串的組合長度分配的內存,那麼這些字符串會被複制到哪裏? 我寫了一個將字符串附加在一起的線性方法和一個平分方法,並定時了這兩種方法。平分法比直線法快2倍。追加過程中是否有任何機制可以解釋這兩種方法的時代如此相似?swift string append mechanics
var start = NSDate().timeIntervalSince1970
let _ = stringMe(400000000, str:"Developers! ")
var end = NSDate().timeIntervalSince1970
var duration = end - start;
print("stringMe takes: \(duration)");
start = NSDate().timeIntervalSince1970
let _ = stringMe2(400000000, str:"Developers! ")
end = NSDate().timeIntervalSince1970
duration = end - start;
print("stringMe2 takes: \(duration)");
func stringMe(n:Int, str:String)-> String {
var string = ""
for _ in 0..<n{
string += str
}
return string
}
func stringMe2(n:Int, str:String)->String
{
var string = str
var currentWritten = 1
while currentWritten < n {
if currentWritten*2>n {
string += stringMe2(n-currentWritten, str: str)
break
}
currentWritten*=2
string+=string
}
return string
}