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

前端 未结 8 1562
我寻月下人不归
我寻月下人不归 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:09

    I would guess that this is as fast as possible:

    let targ = Character("1")
    let input: String = "001" // your real string goes here
    let inputchars = Array(input.characters)
    var output:[Bool] = Array.init(count: inputchars.count, repeatedValue: false)
    inputchars.withUnsafeBufferPointer {
        inputbuf in
        output.withUnsafeMutableBufferPointer {
            outputbuf in
            var ptr1 = inputbuf.baseAddress
            var ptr2 = outputbuf.baseAddress
            for _ in 0..

    The reason is that, thanks to the use of buffer pointers, we are simply cycling through contiguous memory, just like the way you cycle through a C array by incrementing its pointer. Thus, once we get past the initial setup, this should be as fast as it would be in C.

    EDIT In an actual test, the time difference between the OP's original method and this one is the difference between

    13.3660290241241
    

    and

    0.219357967376709
    

    which is a pretty dramatic speed-up. I hasten to add, however, that I have excluded the initial set-up from the timing test. This line:

    let inputchars = Array(input.characters)
    

    ...is particularly expensive.

提交回复
热议问题