Report abuse

benchmark


			
require 'benchmark'

total = (ENV['TOTAL'] || 100_000).to_i

STRING = "rdnqsp uxq\nhnokjirs\nb c6rlh|4c@jcb av8\nPvunszwijhy lz  kdgy7hlKlR nzqxg\ndqldeg nm-yg vmnb mk gdrn  x"

class String
  def while_loop
    i = 0
    while i < @bytes
      char = @data[i]
      i += 1
    end
  end
end

Benchmark.bmbm do |x|
  x.report("loop") do
    total.times do |i|
      i
    end
  end

  x.report("while_loop") do
    total.times do |i|
      STRING.while_loop
    end
  end

  x.report("each_byte") do
    total.times do |i|
      STRING.each_byte { |c| c }
    end
  end
end

result


			
68-26-244-235:rubinius brian$ shotgun/rubinius bm_each_byte.rb 
Rehearsal ----------------------------------------------
loop         0.021077   0.000000   0.021077 (  0.021173)
while_loop   1.142466   0.000000   1.142466 (  1.142510)
each_byte    2.705700   0.000000   2.705700 (  2.705811)
------------------------------------- total: 3.869243sec

                 user     system      total        real
loop         0.021191   0.000000   0.021191 (  0.021194)
while_loop   1.071735   0.000000   1.071735 (  1.071749)
each_byte    2.667623   0.000000   2.667623 (  2.667608)