gabriele renzi said:
Robert Klemme ha scritto:
did you (both) also considered that the undelying OS' caching strategy
may have some effect on this results?
Good point. Now:
require 'benchmark'
require 'stringio'
st = StringIO.new
100000.times { st << "foo " * rand(10) << "\n" }
Benchmark.bm(7) do |x|
st.seek 0
x.report("readlines:") do
st.readlines.each {|l| l.chomp!}
end
st.seek 0
x.report("inject:") do
st.inject([]) {|ar,line| line.chomp!; ar << line}
end
st.seek 0
x.report("inject2:") do
st.inject([]) {|ar,line| ar << line.chomp!}
end
st.seek 0
x.report("foreach:") do
st.each{|line| (lines||=[]) << line.chomp!}
end
st.seek 0
x.report("foreach2:") do
lines = []
st.each{|line| lines << line.chomp!}
end
end
Yields on my machine:
$ ruby filetest2.rb
user system total real
readlines: 0.031000 0.000000 0.031000 ( 0.032000)
inject: 0.078000 0.000000 0.078000 ( 0.077000)
inject2: 0.063000 0.000000 0.063000 ( 0.051000)
foreach: 0.062000 0.000000 0.062000 ( 0.073000)
foreach2: 0.094000 0.000000 0.094000 ( 0.088000)
$ ruby filetest2.rb
user system total real
readlines: 0.031000 0.000000 0.031000 ( 0.032000)
inject: 0.078000 0.000000 0.078000 ( 0.079000)
inject2: 0.047000 0.000000 0.047000 ( 0.051000)
foreach: 0.078000 0.000000 0.078000 ( 0.074000)
foreach2: 0.078000 0.000000 0.078000 ( 0.084000)
$ ruby filetest2.rb
user system total real
readlines: 0.281000 0.016000 0.297000 ( 0.303000)
inject: 0.844000 0.015000 0.859000 ( 0.855000)
inject2: 1.094000 0.000000 1.094000 ( 1.174000)
foreach: 0.906000 0.000000 0.906000 ( 0.905000)
foreach2: 0.375000 0.000000 0.375000 ( 0.393000)
$ ruby filetest2.rb
user system total real
readlines: 0.344000 0.032000 0.376000 ( 0.417000)
inject: 0.875000 0.000000 0.875000 ( 0.974000)
inject2: 0.891000 0.031000 0.922000 ( 0.943000)
foreach: 0.906000 0.016000 0.922000 ( 0.915000)
foreach2: 0.391000 0.000000 0.391000 ( 0.387000)
$ ruby filetest2.rb
user system total real
readlines: 0.312000 0.000000 0.312000 ( 0.304000)
inject: 0.860000 0.000000 0.860000 ( 0.858000)
inject2: 0.921000 0.015000 0.936000 ( 0.943000)
foreach: 0.922000 0.000000 0.922000 ( 0.916000)
foreach2: 0.391000 0.000000 0.391000 ( 0.384000)
Hm...
robert