From: "Joe Wölfel" Date: 2008-09-21T09:54:05+09:00 Subject: Re: for or each? --Apple-Mail-2-986064083 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On 20 sept. 08, at 20:10, _why wrote: > > Actually for loops are faster than `each`. Since it doesn't > introduce a block, there's no extra scope created. Not much faster, > but they are used in the computer language shootout, for instance. > _why > Any thoughts on the Ruby 1.9 result? It seems like 'each' is much faster than either the original for loop we started talking about, or the non-index based one (for loop 2). You can run the code below if you like. Ruby 1.9 output: Rehearsal -------------------------------------------------- for loop 1.240000 0.000000 1.240000 ( 1.240751) for loop 2 1.180000 0.000000 1.180000 ( 1.176560) each 0.510000 0.010000 0.520000 ( 0.512496) ----------------------------------------- total: 2.940000sec user system total real for loop 1.190000 0.010000 1.200000 ( 1.197695) for loop 2 1.180000 0.000000 1.180000 ( 1.177620) each 0.510000 0.000000 0.510000 ( 0.508858) Ruby 1.86 output: Rehearsal -------------------------------------------------- for loop 2.840000 0.040000 2.880000 ( 2.880437) for loop 2 1.660000 0.000000 1.660000 ( 1.661229) each 1.750000 0.010000 1.760000 ( 1.755502) ----------------------------------------- total: 6.300000sec user system total real for loop 2.300000 0.000000 2.300000 ( 2.307566) for loop 2 1.660000 0.010000 1.670000 ( 1.666218) each 1.760000 0.000000 1.760000 ( 1.760356) 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 "for loop 2" do x = 0 100.times do for i in a x += i end end end bench.report "each" do x = 0 100.times do a.each do |i| x += i end end end end --Apple-Mail-2-986064083--