Last active
August 29, 2015 14:11
-
-
Save yuki24/e8d89597efa0fbdfe775 to your computer and use it in GitHub Desktop.
Array#max vs if
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark/ips' | |
Benchmark.ips do |x| | |
NEGATIVE = "-1" | |
ZERO = "0" | |
ONE = "1" | |
TWO = "2" | |
x.report("Array#max ( -1)") { [NEGATIVE.to_i, 1].max - 1 } | |
x.report("Array#max ( 0)") { [ ZERO.to_i, 1].max - 1 } | |
x.report("Array#max ( 1)") { [ ONE.to_i, 1].max - 1 } | |
x.report("Array#max ( 2)") { [ TWO.to_i, 1].max - 1 } | |
x.report("Array#max (nil)") { [ NIL.to_i, 1].max - 1 } | |
x.report("with if ( -1)") do | |
num = NEGATIVE.to_i | |
num < 0 ? 0 : (num - 1) | |
end | |
x.report("with if ( 0)") do | |
num = ZERO.to_i | |
num < 0 ? 0 : (num - 1) | |
end | |
x.report("with if ( 1)") do | |
num = ONE.to_i | |
num < 0 ? 0 : (num - 1) | |
end | |
x.report("with if ( 2)") do | |
num = TWO.to_i | |
num < 0 ? 0 : (num - 1) | |
end | |
x.report("with if (nil)") do | |
num = NIL.to_i | |
num < 0 ? 0 : (num - 1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 2.1.5:
Rubinius 2.4.1:
JRuby head:
JRuby 1.7.16.2: