JuliaLang/julia — pull request #2107 by diegozea (2013-01-22 19:12:43+00:00)
Title: Faster strchr

```
julia> s=randstring(10000).data;

julia> memchr(s,'C',1)
178

julia> function f(s,c,i)
for j in i:length(s)
if s[j]==c
return j
end
end
return 0
end

julia> f(s,'C',1)
178

julia> benchmark(()->memchr(s,'C',1),()->f(s,'C',1),"cmp","memchr","for",1000)
memchr 1.4216811568648726e-6, 1.6298568674055228e-8
for 9.931015133393878e-7, 2.4488361237383283e-8
memchr wins to for on the 12.242798353909464% of runnings
for wins to memchr on the 53.18930041152263% of runnings
Ties: 34.5679012345679%

```

I read about memchr comparing more than one byte per cycle (value depends on 32 o 64 bits computer)[1]. Maybe in my memchr is more efficient, but... Looks like a simple for can be a little more faster on Julia. Maybe is good if you test the same too, maybe is slower only on my computer.
About other topic on [1]... In Julia do 'a'|32 is a little more slower than do 'a'-32

[1] http://www.codemaestro.com/articles/21

P.S.: The benchmark function:
```
function benchmark(f::Function, f2::Function, category::String, name::String, name2::String, N::Int)
choosed = rand(2N) .<= .5
N1= sum(choosed)
N2= 2N - N1
times1 = zeros(N1)
times2 = zeros(N2)
f() # Call once to force JIT compilation
f2()
i=1
j=1
for itr in 1:2N
gc()
if choosed[itr]
times1[i] = @elapsed f()
i += 1
else
times2[j] = @elapsed f2()
j += 1
end
end
println("$name $(mean( times1 )), $(std( times1 )/sqrt(length(times1)))")
println("$name2 $(mean( times2 )), $(std( times2 )/sqrt(length(times2)))")
println("$name wins to $name2 on the $(N1 > N2 ? mean( times1[1:N2] .< times2 )*100 : mean( times1 .< times2[1:N1] )*100)% of runnings")
println("$name2 wins to $name on the $(N1 > N2 ? mean( times1[1:N2] .> times2 )*100 : mean( times1 .> times2[1:N1] )*100)% of runnings")
println("Ties: $(N1 > N2 ? mean( times1[1:N2] .== times2 )*100 : mean( times1 .== times2[1:N1] )*100)%")

end
```

More times comparisons:
```
julia> function strchr_2(s::ASCIIString, c::Char, i::Integer)
d = s.data
if c < 0x80
for j in i:length(d)
if d[j]==c
return j
end
end
return 0
else
return 0
end
end

julia> strchr(s,'C',1)
227

julia> strchr_2(s,'C',1)
227

julia> benchmark(()->strchr(s,'C',1),()->strchr_2(s,'C',1),"cmp","memchr","for",1000)
memchr 2.103140859892874e-6, 1.4044128297947677e-8
for 1.7999422432172417e-6, 1.3410130651872449e-8
memchr wins to for on the 20.404040404040405% of runnings
for wins to memchr on the 47.070707070707066% of runnings
Ties: 32.525252525252526%
```