为什么这个简单的快速嵌套for循环这么慢

问题描述 投票:0回答:1

我有一个非常基本的嵌套 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
ios swift mobile-development
1个回答
0
投票

这里存在许多潜在的性能问题:

  1. 调试版本未优化。因此,循环比优化的发布版本慢得多。检查您方案的“运行”设置。
  2. 你在一个循环中循环,这是低效的。建立一个字典,你将享受每个字符替换的 O(1) 性能。
  3. 构建逐个字符附加的字符串效率低下,导致字符串缓冲区的大小被多次调整。我们经常会“储备容量”,以减少这种影响。

例如,我的简单方法:

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] })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.