From: Intransition Date: 2010-02-07T00:03:20+09:00 Subject: Re: Fastest way to iterate over a range in steps On Feb 6, 8:40 am, Robert Klemme wrote: > On 02/05/2010 09:19 PM, Intransition wrote: > > > > > On Feb 5, 2:52 pm, Robert Klemme wrote: > > >> I think we are seeing an effect of the missing call to the block that > >> happens on each iteration for #step approaches.  The while loop does not > >> have this overhead. > > > Might consider how #succ plays into this as well. > > Good idea! > > robert@fussel:~$ ruby19 xx.rb > Rehearsal -------------------------------------------------- > while           15.550000   0.060000  15.610000 ( 22.225998) > succ            66.930000   0.340000  67.270000 ( 93.726408) > range step      31.930000   0.080000  32.010000 ( 44.892588) > step            30.650000   0.140000  30.790000 ( 43.183693) > --------------------------------------- total: 145.680000sec > >                       user     system      total        real > while           15.430000   0.080000  15.510000 ( 21.889805) > succ            67.170000   0.440000  67.610000 ( 95.958702) > range step      32.090000   0.160000  32.250000 ( 44.213130) > step            30.670000   0.110000  30.780000 ( 43.151260) > robert@fussel:~$ cat xx.rb > > require 'benchmark' > > LI = 1000000000 > ST = 5 > > Benchmark.bmbm 15 do |b| >    b.report "while" do >      i = 0 >      while i < LI >        i += ST >      end >    end > >    b.report "succ" do >      i = 0 >      while i < LI >        i = i.succ >      end >    end > >    b.report "range step" do |b| >      (0...LI).step ST do |i| i >      end >    end > >    b.report "step" do |b| >      0.step LI, ST do |i| i >      end >    end > end To be fair maybe add a reference to i. > robert@fussel:~$ > > ... or rather not. :-) Good to know too. Though actually I was wondering if range#step uses #succ? I think in the case of integers it's optimized to not use #succ, but there can be different types of ranges (eg. String ranges) and in those cases it does. Sometime back I suggested that #succ take an optional parameter to specify how many times to #succ. This would allow classes like Fixnum to optimize multiple steps. In any case I find it striking how much faster while is. It's understandable that there is some overhead accompany the use of a block. But that much?