Last active
December 29, 2015 17:29
-
-
Save akshay-vishnoi/7704579 to your computer and use it in GitHub Desktop.
#type_cast - improve performance & readability
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' | |
def old_method(a) | |
return 'abc' unless a == true || a == false | |
a ? 1 : 0 | |
end | |
def new_method(a) | |
case a | |
when TrueClass | |
1 | |
when FalseClass | |
0 | |
else | |
'abc' | |
end | |
end | |
a = true | |
b = false | |
c = 'abc' | |
TIMES = 500_000 | |
Benchmark.bmbm do |b| | |
b.report('old') do | |
TIMES.times do | |
old_method(a) | |
old_method(b) | |
old_method(c) | |
end | |
end | |
b.report('new') do | |
TIMES.times do | |
new_method(a) | |
new_method(b) | |
new_method(c) | |
end | |
end | |
end | |
Rehearsal --------------------------------------- | |
old 0.510000 0.000000 0.510000 ( 0.509637) | |
new 0.430000 0.000000 0.430000 ( 0.426565) | |
------------------------------ total: 0.940000sec | |
user system total real | |
old 0.480000 0.000000 0.480000 ( 0.475493) | |
new 0.400000 0.000000 0.400000 ( 0.401554) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment