Saturday, 10 December 2016

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



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 input: String = "001"

let output: [Bool] = [false, false, true]


My naive attempt was this:



input.characters.map { $0 == "1" }


But this is a lot slower than I'd like. My profiling has shown me that the map is where the slowdown is, but I'm not sure how much simpler I can make that.




I feel like this would be wicked fast without Swift's/ObjC's overhead. In C, I think this is a simple for loop where a byte of memory is compared to a constant, but I'm not sure what the functions or syntax is that I should be looking at.



Is there a way to do this much faster?



UPDATE:



I also tried a



output = []
for char in input.characters {

output.append(char == "1")
}


And it's about 15% faster. I'm hoping for a lot more than that.


Answer



This is faster:



// Algorithm 'A'
let input = "0101010110010101010"

var output = Array(count: input.characters.count, repeatedValue: false)
for (index, char) in input.characters.enumerate() where char == "1" {
output[index] = true
}


Update: under input = "010101011010101001000100000011010101010101010101"



0.0741 / 0.0087, where this approach is faster that author's in 8.46 times. With bigger data correlation more positive.




Also, with using nulTerminatedUTF8 speed a little increased, but not always speed higher than algorithm A:



// Algorithm 'B'
let input = "10101010101011111110101000010100101001010101"
var output = Array(count: input.nulTerminatedUTF8.count, repeatedValue: false)
for (index, code) in input.nulTerminatedUTF8.enumerate() where code == 49 {
output[index] = true
}



In result graph appears, with input length 2196, where first and last 0..1, A – second, B – third point.
A: 0.311sec, B: 0.304sec



Algorithm comparison graph


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...