jdfrens
1/10/2018 - 4:49 PM

benchmark Ruby compact and to_i solutions for finding max

Ruby 2.2.7:

              user     system      total        real
to_i      7.890000   0.020000   7.910000 (  7.916156)
compact   7.870000   0.010000   7.880000 (  7.890511)

Ruby 2.4.2:

              user     system      total        real
to_i      2.120000   0.000000   2.120000 (  2.132754)
compact   3.930000   0.010000   3.940000 (  3.937682)
require 'benchmark'

foo = [[8, nil], [8, 99]] * 10_000_000

Benchmark.bm(7) do |x|
  x.report("to_i") do
    foo.each { |(a, b)| [a, b.to_i].max }
  end
  x.report("compact") do
    foo.each { |(a, b)| [a, b].compact.max }
  end
end