Skip to content

Instantly share code, notes, and snippets.

@tadman
Created June 30, 2015 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tadman/54445fba7b65d757635d to your computer and use it in GitHub Desktop.
Save tadman/54445fba7b65d757635d to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'benchmark'
COUNT = 1000
LOOP = 1000
def case_method_rb
[
"def case_method(x)",
"case (x)",
(0..COUNT).collect { |v| "when #{v}\nx+10" },
"end",
"end"
].flatten.join("\n")
end
def if_method_rb
[
"def if_method(x)",
(0..COUNT).each_with_index.collect { |v,i|
case (i)
when 0
"if (x == #{v})\n\tx+10"
else
"elsif (x == #{v})\n\tx+10"
end
},
"end",
"end"
].flatten.join("\n")
end
LOOKUP = Hash[
(0..COUNT).collect do |i|
[ i, i + 10 ]
end
]
def hash_method(x)
LOOKUP[x]
end
eval case_method_rb
eval if_method_rb
# puts case_method_rb
# puts if_method_rb
Benchmark.bm do |x|
x.report(:case) { LOOP.times { COUNT.times { |i| case_method(i) } } }
x.report(:if) { LOOP.times { COUNT.times { |i| if_method(i) } } }
x.report(:hash) { LOOP.times { COUNT.times { |i| hash_method(i) } } }
end
# user system total real
# case 0.120000 0.000000 0.120000 ( 0.120738)
# if 6.790000 0.010000 6.800000 ( 6.795076)
# hash 0.130000 0.000000 0.130000 ( 0.132431)
# [Finished in 7.2s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment