我有一个很长的字符串(有时超过 1000 个字符),我想将其转换为 bool 值数组。它需要非常快速地多次执行此操作。
let input: String = "001"
let output: [Bool] = [false, false, true]
我天真的尝试是这样的:
input.characters.map { $0 == "1" }
但这比我希望的要慢很多。我的分析表明 map
是减速的地方,但我不确定我能把它简化多少。
如果没有 Swift/ObjC 的开销,我觉得这会非常快。在 C 中,我认为这是一个简单的 for
循环,其中将内存字节与常量进行比较,但我不确定我应该查看的函数或语法是什么。
有没有办法更快地做到这一点?
更新:
我也试过
output = []
for char in input.characters {
output.append(char == "1")
}
而且速度提高了大约 15%。我希望得到更多。
最佳答案
这样更快:
// Algorithm 'A'
let input = "0101010110010101010"
var output = Array<Bool>(count: input.characters.count, repeatedValue: false)
for (index, char) in input.characters.enumerate() where char == "1" {
output[index] = true
}
更新:在input = "010101011010101001000100000011010101010101010101"
0.0741/0.0087,这种方法比作者的方法快 8.46 倍。数据越大,相关性越正。
此外,使用 nulTerminatedUTF8
速度略有提高,但速度并不总是高于算法 A:
// Algorithm 'B'
let input = "10101010101011111110101000010100101001010101"
var output = Array<Bool>(count: input.nulTerminatedUTF8.count, repeatedValue: false)
for (index, code) in input.nulTerminatedUTF8.enumerate() where code == 49 {
output[index] = true
}
在结果图中出现,输入长度2196,其中第一个和最后一个0..1,A – 第二个,B – 第三个点。 A:0.311秒,B:0.304秒
关于ios - 将两个字符的字符串转换为 bool 数组的快速方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074136/