The calendar is gone.
Click here to view posts


Iteration woes
My world has just been turned upside down. I need to start benchmarking some real data. I am using large arrays of random. Anyway, after trying to find the max number in array I found using the each method was slower then sorting. I then wondered if different types of iteration would be faster. So after some wings for breakfast at the Seattle airport I created another benchmark.
n = 10000
start_array = Array.new(6000)
(0...6000).each{|i| start_array[i]=rand(4000000)}
require "benchmark"
Benchmark.bm(1) do |test|
  test.report("each:") do
    n.times{
      start_array.each{|x|
          x
        }
    }
  end
  test.report("for:") do
    n.times{
      for x in start_array
        x
      end
    }
  end
  test.report("each_index:") do
    n.times{
      start_array.each_index{|i|
          start_array[i]
        }
    }
  end
  test.report("range each:") do
    n.times{
      (0...start_array.size).each{|i|
          start_array[i]
        }
    }
  end
  test.report("each_with_index:") do
    n.times{
      start_array.each_with_index{|x,i|
          x
        }
    }
  end
end

And the results?
#       user     system      total        real
#each: 14.360000   0.070000  14.430000 ( 14.516698)
#for: 11.880000   0.040000  11.920000 ( 11.919000)
#each_index: 44.280000   0.160000  44.440000 ( 44.451407)
#range each: 44.760000   0.190000  44.950000 ( 45.039539)
#each_with_index: 46.560000   0.320000  46.880000 ( 47.269472)


If I left out any ways to iterate please let me know.