What is a fast way to convert a string of two characters to an array of booleans?

前端 未结 8 1705
我寻月下人不归
我寻月下人不归 2021-02-04 10:24

I have a long string (sometimes over 1000 characters) that I want to convert to an array of boolean values. And it needs to do this many times, very quickly.

let         


        
8条回答
  •  我寻月下人不归
    2021-02-04 11:15

    This should be a little faster than the enumerate() where char == "1" version (0.557s for 500_000 alternating ones and zeros vs. 1.159s algorithm 'A' from diampiax)

    let input = inputStr.utf8
    let n = input.count
    var output = [Bool](count: n, repeatedValue: false)
    let one = UInt8(49) // 1
    for (idx, char) in input.enumerate() {
        if char == one { output[idx] = true }
    }
    

    but it's also a lot less readable ;-p

    edit: both versions are slower than the map variant, maybe you forgot to compile with optimizations?

提交回复
热议问题