From: "Joe Wölfel" Date: 2008-09-21T07:26:03+09:00 Subject: Re: for or each? You can try my test if you like. I haven't checked it carefully. But it does seem like 'each' is much faster under both ruby 1.86 and ruby 1.9. The code is below. require 'rubygems' require 'benchmark' a = (1..10000).to_a Benchmark.bmbm 15 do |bench| bench.report "for loop" do x = 0 100.times do for i in 0...(a.size) x += a[i] end end end bench.report "each" do x = 0 100.times do a.each do |i| x += i end end end end Joe On 20 sept. 08, at 18:17, Phlip wrote: > Joe Wölfel wrote: > >> It's interesting that array access using 'each' seems to be much >> faster on my machine. > > Does 'for' reevaluate its range after each tick? That would give > 'for' a single technical advantage over .each, in the very rare > chance you need that. > > Otherwise, where does the time go? > > A quick experiment with RubyNode just showed Ruby generates > different opcodes for 'each' and 'for'. (By contrast, the notorious > ternary operator, ? :, generates the same opcodes as an equivalent > 'if then else end' construction.) > > -- > Phlip >