我有一个非常基本的嵌套 for 循环迭代 80K 长字符串。这个循环最多需要 2-3 毫秒,但在我的 iPhone 上需要 10 秒。对于智能手机来说,这是一个莫名其妙的时代。为什么会发生这种情况?这是代码。
let cyph_1 : [Character] = my_array1 // 65 characters
let cyph_2 : [Character] = my_array2 // 65 characters
var temp_2 = ""
var temp_1 = "80K long string, not that long"
for k in 0 ..< temp_1.count
{
var exists = false
let some_char = temp_1_characters[k]
for m in 0 ..< cyph_2.count
{
if (cyph_2[m] == some_char)
{
temp_2.append(cyph_1[m])
exists = true
break
}
}
if (!exists)
{
temp_2 += "\(some_char)"
}
}
temp_1 = temp_2
这里存在许多潜在的性能问题:
例如,我的简单方法:
class Cypher {
let encodeKey: [Character: Character]
let decodeKey: [Character: Character]
init(cyph1: [Character], cyph2: [Character]) {
encodeKey = Dictionary(uniqueKeysWithValues: zip(cyph1, cyph2))
decodeKey = Dictionary(uniqueKeysWithValues: zip(cyph2, cyph1))
}
func encode(_ input: String) -> String {
String(input.compactMap { encodeKey[$0] })
}
func decode(_ input: String) -> String {
String(input.compactMap { decodeKey[$0] })
}
}