From: Gennady Date: 2004-08-04T10:19:53+09:00 Subject: Re: Fastest way to reverse-process a string? Ara.T.Howard wrote: > On Wed, 4 Aug 2004, Lloyd Zusman wrote: > >> 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? >> >> Thanks in advance. >> >> >> -- >> Lloyd Zusman >> ljz@asfast.com >> God bless you. > > > ~ > ruby -e 's="raboof"; (s.size - 1).downto(0){|i| print s[i].chr}; puts' > foobar > If you add this as a fourth benchmark x.report("4") { size = str.size - 1 100000.times { size.downto(0) { |_index| str[_index].chr } } } The result will be: user system total real 1 2.630000 0.000000 2.630000 ( 2.627852) 2 2.660000 0.000000 2.660000 ( 2.659415) 3 1.600000 0.000000 1.600000 ( 1.597412) 4 1.840000 0.000000 1.840000 ( 1.845511) So this algorithm is next to the fastest one based on each_byte. Gennady. > > -a > -- > =============================================================================== > > | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov > | PHONE :: 303.497.6469 > | A flower falls, even though we love it; > | and a weed grows, even though we do not love it. | --Dogen > =============================================================================== > >