From: Robert Klemme Date: 2004-08-04T16:36:32+09:00 Subject: Re: Fastest way to reverse-process a string? "Lloyd Zusman" schrieb im Newsbeitrag news:m3wu0f690d.fsf@asfast.com... > "Mehr, Assaph (Assaph)" 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? 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 } } } x.report("4") { 100000.times { (str.length-1).downto(0) {|idx| ch = str[idx]} } } x.report("5") { 100000.times { len = str.size; for idx in 1..len ; ch = str[len-idx] end } } end user system total real 1 6.828000 0.000000 6.828000 ( 6.907000) 2 6.891000 0.000000 6.891000 ( 6.936000) 3 5.078000 0.000000 5.078000 ( 5.098000) 4 2.281000 0.000000 2.281000 ( 2.287000) 5 3.391000 0.000000 3.391000 ( 3.395000) => 4 robert