New paste Repaste Download
require 'benchmark'
letters = [*?A..?Z]
str = 1_000_000.times.map { letters.sample }.join
Benchmark.bm do |x|
  x.report("with_index") { str.each_char.with_index.sum{|c, i| c.ord + i + 1} }
  x.report("zip(1..)")   { str.each_char.zip(1..).sum{|c, i| c.ord + i} }
  x.report("bytes.with_index") { str.each_byte.with_index.sum{|b, i| b + i + 1} }
  x.report("bytes.zip(1..)")   { str.each_byte.zip(1..).sum{|b, i| b + i} }
end
__END__
                      user     system      total        real
with_index        0.188644   0.000984   0.189628 (  0.189780)
zip(1..)          0.479187   0.041009   0.520196 (  0.520911)
bytes.with_index  0.097072   0.012951   0.110023 (  0.110138)
bytes.zip(1..)    0.334842   0.009997   0.344839 (  0.345032)
Filename: None. Size: 762b. View raw, , hex, or download this file.

This paste expires on 2025-07-20 07:12:52.873284. Pasted through web.