我有一个长字符串(有时超过1000个字符),我想转换为一个布尔值数组.而且它需要很多次,很快.
- let input: String = "001"
- let output: [Bool] = [false,false,true]
我天真的尝试是这样的:
- input.characters.map { $0 == "1" }
但这比我想要的要慢很多.我的剖析告诉我,地图是减速的地方,但我不知道我能做多么简单.
我觉得如果没有Swift’s / ObjC的开销,这样做会很快.在C中,我认为这是一个简单的循环,其中一个字节的内存与一个常量进行比较,但我不知道我应该看的是什么函数或语法.
有更好的办法吗?
更新:
我也试过了
- 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
- }
更新:under input =“010101011010101001000100000011010101010101010101”
0.0741 / 0.0087,这种方法比作者的8.46倍快.随着数据相关性的增加,
另外,使用nulTerminatedUTF8速度有点增加,但并不总是比算法A高:
- // Algorithm 'B'
- let input = "10101010101011111110101000010100101001010101"
- var output = Array<Bool>(count: input.nulTerminatedUTF8.count,code) in input.nulTerminatedUTF8.enumerate() where code == 49 {
- output[index] = true
- }
在结果图中出现,输入长度为2196,其中第一和最后一个0..1,A – 秒,B – 第三点.
A:0.311秒,B:0.304秒