Firstly, the above is quite inefficient. It collects the entire string into a vector of Char
s, then runs isdigit
on every single character, creating another temporary array, and then, finally, runs all
on the output of this.
Instead, avoid collecting anything (in fact, if your code contains collect
you are probably wasting time):
all(isdigit, "ABC123")
This will check the first character, and immediately bail out with zero allocations. Compare performance here:
julia> @btime all(isdigit.(collect($str)))
82.505 ns (3 allocations: 176 bytes)
false
julia> @btime all(isdigit, $str)
8.500 ns (0 allocations: 0 bytes)
false
Key to good performance is to avoid unnecessary intermediate allocations, and in the first example, you have got three of them.
As for the parsing part, I don’t understand why you need that at all. If all characters in a string are digits, then it’s a positive integer, so you only need
ispositiveinteger(str) = all(isdigit, str)
julia> ispositiveinteger("12345")
true
julia> ispositiveinteger("-12345")
false
Or do you need to check for whitespace, underscores, etc?
In fact, parse(Int, str)
might ruin things, because of potential overflow:
julia> parse(Int, "9223372036854775808")
ERROR: OverflowError: overflow parsing "9223372036854775808"
julia> ispositiveinteger("9223372036854775808") # this still works
true