I wonder why there is no multi-pair version of replace
for strings. Anyways, the straightforward
function h(s)
snew = replace(s, 'o'=>'L')
return replace(snew, 'a'=>'o')
end
is already ~3x faster than the other Julia implementation in this thread:
using BenchmarkTools
function g(s, tar, rep)
@assert length(tar) == length(rep)
replace(collect(s), Dict(zip(tar,rep))...) |> join
end
function h(s)
snew = replace(s, 'o'=>'L')
return replace(snew, 'a'=>'o')
end
@btime g("The cat sat on the mat", "ao", "oL"); # 1.660 μs
@btime h("The cat sat on the mat"); # 527.368 ns
Running your perl script (after removing the print statements), I get: 15-31 ms
which is much slower. I don’t know if the perl benchmark is any good (I don’t know how to properly benchmark in perl). But taking it for what it is, the Julia implementation h
is more than 2500x faster.