"Mehr, Assaph (Assaph)" <assaph / avaya.com> writes:

>> In a ruby program I'm writing, I want to parse a string in reverse
>> and feed each of its individual characters through a state machine.
>> A "hammer and tongs" solution looks like this:
>>  string.reverse.split(//).each {
>>    |ch|
>>    feedIntoStateMachine(ch)
>>  }
>> However, this seems rather inefficient.  Does anyone know of a faster
>> algorithm for this in ruby?
>
> Have you tried benchmark?

I can only benchmark algorithms when I have more than one algorithm to
compare.  I only thought of the one algorithm that I mentioned in my
original post, and so I had nothing to benchmark it against.

I can easily do the benchmarking, and I was not asking anyone to do it
for me.  I wrote my email because I was looking for algorithm
suggestions, such as the third one that you mentioned.  I was previously
unaware of 'each_byte'.  I also didn't think of trying the split('')
version.

Thank you for these suggestions.

Can anyone think of other ways to do this?  Is there something really
clever that doesn't require 'reverse', perhaps?

I'll benchmark any and all things that I come across.  And I'll be
digging around myself, as well.

Thanks again to all.



> require 'benchmark'
> include Benchmark
>
> str = "Hammer and tongs"
>
> bm(7) do |x|
>   x.report("1") { 100000.times { str.reverse.split(//).each { |ch| ch }
> } }
>   x.report("2") { 100000.times { str.reverse.split('').each { |ch| ch }
> } }
>   x.report("3") { 100000.times { str.reverse.each_byte { |ch| ch.chr } }
> }
> end
>
>              user     system      total        real
> 1        4.094000   0.000000   4.094000 (  4.109000)
> 2        4.125000   0.015000   4.140000 (  4.141000)
> 3        2.375000   0.000000   2.375000 (  2.391000)

-- 
 Lloyd Zusman
 ljz / asfast.com
 God bless you.