I tried this on my machine with a slightly modified ruby script:
===
# simulate 'ruby --version'
puts "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
require 'benchmark'
n = 10**6
a = [
{:name => "each ",
roc => proc{ (0...n).each{|x| x}}},
{:name => "for ",
roc => proc{ for x in 0...n; x ;end }},
{:name => "times ",
roc => proc{ n.times{|x| x}}}
]
a.each {
|o| puts "#{o[:name]} #{Benchmark.measure(&o[
roc])}"
}
puts
a.reverse_each {
|o| puts "#{o[:name]} #{Benchmark.measure(&o[
roc])}"
}
puts <<END
Csaba's benchmark figures were:
ruby 1.8.2 (2004-12-25) [i686-linux]
each 0.370000 0.000000 0.370000 ( 0.376541)
for 0.320000 0.000000 0.320000 ( 0.339880)
times 0.370000 0.000000 0.370000 ( 0.391311)
END
===
Running this:
steve@ruby2 ~/Documents/src/Ruby $ uname -a
Linux ruby2 2.6.10-gentoo-r6 #3 Thu Feb 24 11:29:50 EST 2005 i686
Pentium III (Coppermine) GenuineIntel GNU/Linux
steve@ruby2 ~/Documents/src/Ruby $ ruby benchmark.rb
ruby 1.8.2 (2004-12-25) [i686-linux]
each 0.780000 0.000000 0.780000 ( 0.850872)
for 0.560000 0.000000 0.560000 ( 0.586458)
times 0.750000 0.000000 0.750000 ( 0.779069)
times 0.750000 0.000000 0.750000 ( 0.831255)
for 0.560000 0.000000 0.560000 ( 0.589044)
each 0.770000 0.000000 0.770000 ( 0.801004)
Csaba's benchmark figures were:
ruby 1.8.2 (2004-12-25) [i686-linux]
each 0.370000 0.000000 0.370000 ( 0.376541)
for 0.320000 0.000000 0.320000 ( 0.339880)
times 0.370000 0.000000 0.370000 ( 0.391311)
For me, "for" is quite alot quicker than either mechanism that uses
blocks. At the moment I'm not really concerned with performance. It's
interesting though. I seem to be running the same version of ruby as
Csaba but my hardware is letting me down - particularly with blocks...
Steve.