by 6gvONxR4sf7o · 5y ago · 0 comments
function longest_word(st::Union{String, SubString{String}})
len = 0
start = 1
@inbounds for i in 1:ncodeunits(st)
if codeunit(st, i) == UInt8(' ')
len = max(len, i - start)
start = i + 1
end
end
max(len, ncodeunits(st) + 1 - start)
end
This takes about 8.2 µs for a 8.5 Kb piece of text on my laptop, but that only works on ASCII text and only treats ' ' as whitespace, not e.g. '\n'. For a more generic one, you can do: function longest_word(st::Union{String, SubString{String}})
len = i = 0
start = 1
for char in st
i += 1
if isspace(char)
len = max(len, i - start)
start = i + 1
end
end
max(len, i + 1 - start)
end
This is 20 µs for the same text, so still only 3 ns per char. The underlying functionality, namely String iteration and the `isspace` function, is also implemented in pure Julia.For example, what other dynamic languages do like verbosely typing everything doesn't really work in Julia (the compiler already knows pretty much every type even without hints), what works is treating the variable as a polymorphic container instead of a dynamic container: you don't know yet what type the variable has (only the behaviour), but whatever it is you should avoid changing it if possible (what they call type stability). Which is kinda why it might not be obvious reading proper high performance Julia code, as it is not something you do to make it fast, but what you don't do (change a variable type, forcing the compiler to create a low performance dynamic box, plus other stuff like global variables).